Upgrading to Redux v6

2019-07-25 09:44发布

问题:

I'm trying to upgrade to Redux V6 but am confused on how to use the createContext function and it's necessity. I know my store is created successfully, but when I try to run my app I get

Could not find "store" in the context of "Connect(ConfiguredApp)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(ConfiguredApp) in connect options.

Which tells me that my provider is not properly passing down the store for connect to grab. What am I doing wrong? Thanks!

import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {ConnectedRouter} from 'connected-react-router';
import {history, store} from './store/store';
import Routes from './routes';

const customContext = React.createContext(null);

render(
  <Provider store={store} context={customContext}>
    <ConnectedRouter history={history} context={customContext}>
      <Routes />
    </ConnectedRouter>
  </Provider>, document.getElementById('app'),
);

回答1:

You almost definitely shouldn't be creating and passing in a custom context instance. That's only if, for some very specific reason, you want to use a context instance other than the default one that React-Redux already uses internally. (A hypothetical reason to do this would be if you are using one store for your whole app component tree, but there's a specific subtree that needs to receive data from a different store instead.)

If you actually wanted to use your own custom context instance, then you would need to pass the same context instance to both <Provider> and each connected component in the app that needs to receive data from that <Provider>.

Looking at the connected-react-router docs, they do claim that in CRR version 6, you can pass a context instance to <ConnectedRouter>, but that shouldn't be necessary here.

More specifically, if you look at the error message, it says the problem is in Connect(ConfiguredApp). So, it's your own connected component that is saying there's a context mismatch.

Ultimately, the answer here is to delete the context arguments from both <Provider> and <ConnectedRouter>. You don't need them.



标签: reactjs redux