使用Redux更改根组件的状态/属性? [英] Changing state/props of root component with Redux?

查看:217
本文介绍了使用Redux更改根组件的状态/属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的根组件可以呈现如下内容:

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>

我正在从后端动态获取this.state.messages(异步,Redux动作+减速器)作为对象.我将其存储在Redux商店中.如何将Redux存储messages传递给this.state.messages(props也会这样做).

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).

绘图扭曲:我不能对此组件使用react-redux connect,因为它是根组件,并且不在<Provider>内(它引入了它),因此,请执行以下操作:

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);

结尾:

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)".

有没有一种以其他理智的方式访问Redux存储的方法?我当时在考虑store.getState(),但它不接受任何参数,并且当我只想获取其中一个状态时,映射所有状态项似乎是一种过大的手段.还是我做错了,毕竟connect应该在这里工作?

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?

推荐答案

您可以创建一个连接的react组件,该组件将包装IntlProvider并将消息传递给它.

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);

用法:

<Provider store={store}>
  <ConnectedIntlProvider locale="en">
    <Router>
      <App>
        // routes
      </App>
    </Router>
  </ConnectedIntlProvider>
</Provider>

这篇关于使用Redux更改根组件的状态/属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆