How to access store in second component in react-redux
我只有一个组件App.js,试图在其中使用redux保存状态。在index.js中,我只为<App />组件设置了存储。
index.js
1 2 3 4 5 6 7
| let store = createStore(scoreReducer);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById("root")
);
registerServiceWorker(); |
我在App.js中有此方法可将状态映射到道具,而道具在App.js内部可用。
App.js
1 2 3
| function mapStateToProps(state) {
return { score: state.score, status: state.status };
} |
到目前为止一切都很好,现在我不确定如何在另一个组件中访问{ this.props.score}吗?
如果要访问另一个组件中的{this.props.score},我需要在index.js和第二个组件中进行哪些更改?
在使用提供程序时,通过使用connect函数,作为提供程序高阶组件的子级的任何组件都可以访问商店属性。
因此您可以在Provider子级的任何组件中添加以下内容,并访问得分道具
1 2 3 4 5
| function mapStateToProps(state) {
return { score: state.score, status: state.status };
}
export default connect(mapStateToProps)(MyComponent) |
但是,如果此其他组件是App组件的直接子代,那么您也可以像
一样将score prop作为prop传递给App到此组件
1
| <MyComponent score={this.props.score}/> |
-
您能建议如何添加Provider的多个子项吗?
-
只需在提供程序组件<Provider store = {store}> <App /> <MyComponent /> </ Provider>中呈现该组件,
-
我们可以像context.store那样访问商店吗?我正在得到Line 94: context is not defined no-undef let store = context.store;
-
不确定如何使用。但是可以肯定的是,上述方法是必经之路
-
恭喜,这个答案比Ive在react-redux上阅读的所有教程和官方文档都要好。包括快速入门,这是完全没有用的。
Provider组件为其所有子组件设置上下文,并在其中提供存储。当您使用高阶组件(HOC)connect时,无论它们如何嵌套,都可以package任何组件并通过提供的mapStateToProps和mapStateToProps访问商店。您也可以使用上下文context.store访问商店,但不建议这样做。最好的方法是使用映射函数和connect(类似于App组件所具有的功能)。
- 我尝试像render() { let store = context.store;一样,但出现错误Line 94: context is not defined no-undef
-
在您的组件中,您需要声明contextTypes,如果您使用的是基于类的组件,则为this.context
-
let store = this.context.store; console.log(store);我在控制台上变得未定义
-
您是否声明了contextTypes?看看这个线程github.com/reactjs/react-redux/issues/