如何在 react-redux 中访问第二个组件中的存储 [英] How to access store in second component in react-redux

查看:43
本文介绍了如何在 react-redux 中访问第二个组件中的存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单独的组件 App.js,我在其中尝试使用 redux 保存状态.在 index.js 中,我只为 组件设置了存储.

I have a single component App.js where I trying to save state using redux. In index.js where I set store for only <App /> component.

index.js

let store = createStore(scoreReducer);

ReactDOM.render(
  <Provider store={store}><App /></Provider>,
  document.getElementById("root")
);
registerServiceWorker();

我在 App.js 中有这个方法来将状态映射到 App.js 中可用的道具.

I have this method in App.js to map state to props which is available inside App.js.

App.js

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

到目前为止一切都很好,现在我不确定如何在另一个组件中访问 { this.props.score} ?

Everything is well so far, now I am not sure how to access { this.props.score} in another component ?

如果我想在另一个组件中访问 {this.props.score} ,我需要在 index.js 和第二个组件中做哪些更改?

What changes I need to do in index.js and second component if I want to access {this.props.score} in another component ?

推荐答案

当您使用 Provider 时,任何属于 Provider 高阶组件的子组件都可以通过使用 connect 访问商店属性功能.

When you are using Provider any component that is children of the Provider Higher Order Component can access the store properties though the use of connect function.

因此您可以在作为 Provider 的子组件的任何组件中添加以下内容并访问 score 属性

So you can add the following in any component that is a child of Provider and access the score prop

function mapStateToProps(state) {
  return { score: state.score, status: state.status };
}

export default connect(mapStateToProps)(MyComponent)

但是,如果另一个组件是 App 组件的直接子组件,那么您也可以将 score prop 作为 prop 传递给该组件来自 App 喜欢

However if this other component is a direct child of App component then you can also pass the score prop as a prop to this component from App like

<MyComponent score={this.props.score}/>

这篇关于如何在 react-redux 中访问第二个组件中的存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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