Changing state/props of root component with Redux?

社会主义新天地 提交于 2019-12-11 15:22:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!