如何在react-redux中访问第二个组件中的存储
我只有一个组件App.js
,试图使用来保存状态redux
。在index.js中,我只为<App />
组件设置存储。
index.js
let store = createStore(scoreReducer);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById("root")
);
registerServiceWorker();
我有这种方法App.js
可以将状态映射到props中,该props在内部App.js
。
App.js
function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
到目前为止一切都很好,现在我不确定如何{ this.props.score}
在另一个组件中访问?
index.js
如果要访问{this.props.score}
另一个组件,我需要在第二个组件中进行哪些更改?
-
使用提供程序时,作为提供程序高阶组件的子级的任何组件都可以通过使用
connect
功能来访问商店属性。因此,您可以在Provider子级的任何组件中添加以下内容,并访问得分道具
function mapStateToProps(state) { return { score: state.score, status: state.status }; } export default connect(mapStateToProps)(MyComponent)
但是,如果该其他组件是该组件的直接子代,
App
那么您也可以将score prop
a作为prop
从App 传递给该组件<MyComponent score={this.props.score}/>