问题
I have my root component that renders something like this:
<Provider store={store}>
<IntlProvider locale="en" messages={this.state.messages}>
<Router>
<App>
// routes
</App>
</Router>
</IntlProvider>
</Provider>
I'm getting this.state.messages dynamically (async, Redux action + reducer) from the back-end as an object. I'm storing it in Redux store. How do I pass the Redux store messages to this.state.messages (props would do as well).
Plot twist: I CAN'T USE react-redux connect with this component, because it's the root component and it's not within <Provider> (it introduces it), so, doing this:
const mapStateToProps = state => {
return {
messages: state.messages
}
}
export default connect(mapStateToProps)(RootComponent);
Ends in:
Uncaught Error: Could not find "store" in either the context or props of "Connect(RootComponent)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(RootComponent)".
Is there a way of accessing Redux store in a different, sane manner? I was thinking about store.getState() but it accepts no arguments and mapping over all the state items seems like an overkill when I want to get just one of them. Or maybe I do something wrong and after all connect should work here?
回答1:
You can create a connected react component that will wrap the IntlProvider, and pass messages to it.
Sample code (haven't tested):
const ConnectedIntlProvider = ({ children, ...props }) => ( // the props contain the messages and the locale
<IntlProvider locale="en" { ...props }>
{ children }
</IntlProvider>
);
const mapStateToProps = state => ({
messages: state.messages
});
export default connect(mapStateToProps)(ConnectedIntlProvider);
Usages:
<Provider store={store}>
<ConnectedIntlProvider locale="en">
<Router>
<App>
// routes
</App>
</Router>
</ConnectedIntlProvider>
</Provider>
来源:https://stackoverflow.com/questions/47495723/changing-state-props-of-root-component-with-redux