Reactjs 在React和Redux中编写关于使用store或connect()的样式?
我是新来React的,对React的写作风格有疑问。 问题是,当从redux获取状态时,哪种书写风格更好或更正常 1) 使用connect()和mapPropsToState()*react redux 2) 使用store和getState() 现在我使用“connect()”,因为许多教程使用“connect()”从Redux传递或获取状态。 但是我认为如果这些组件有子组件,那么道具就必须像不使用Redux一样传递给子组件 它扼杀了redux可以从任何层(任何地方)获取状态的一个优点 给她打个电话 index.jsReactjs 在React和Redux中编写关于使用store或connect()的样式?,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我是新来React的,对React的写作风格有疑问。 问题是,当从redux获取状态时,哪种书写风格更好或更正常 1) 使用connect()和mapPropsToState()*react redux 2) 使用store和getState() 现在我使用“connect()”,因为许多教程使用“connect()”从Redux传递或获取状态。 但是我认为如果这些组件有子组件,那么道具就必须像不使用Redux一样传递给子组件 它扼杀了redux可以从任何层(任何地方)获取状态的一个优点 给她打
export let store=createStore(reducer);
render.js
类父exteds.Component{
render(){
返回(
)
}
}
类子exteds react.Component{
render(){
返回(
或
)
}
}
函数MapStateTops(状态){
console.log(状态)
返回{…状态};
}
功能图DispatchToprops(调度){
返回bindActionCreators({
test:testfunction
},调度)
};
export const renderFormGenerator=connect(MapStateTrops,mapDispatchToProps)(渲染);
随着应用程序的增长,最好使用react-redux,而不是手动将store传递给所有单个组件
也就是说,您的连接中需要做一些小的更改。您希望接收动作创建者的组件应该位于您的渲染
i、 e而不是这个
connect(MapStateTrops、mapDispatchToProps)(渲染)
这样做
connect(MapStateTrops、mapDispatchToProps)(myComponent)
通过这种方式,您可以访问myComponent中的动作创建者,如This.props.myAction()
我同意你的担心,如果这样使用,你将不得不再次手动将动作作为道具传递给孩子们
但是,通过创建子容器并再次使用connect,可以很容易地解决这个问题<代码>连接(MapStateTrops、mapDispatchToProps)(myChildComponent)
我建议您仔细阅读丹·阿布拉莫夫的这篇优秀文章。您也可以在儿童中使用
connect
。谢谢您的回复!这意味着如果没有传递到儿童组合中,它可以使用?是的,当然。您可以在任何组件中使用connect
访问redux状态,并将其传递给组件的props
。谢谢。在我的代码中,当不将道具传递给子级时,会显示错误消息,如“this.props.test is not function”,因此我认为它也必须传递给子级。也许我的代码中有一些bug,所以我会检查它们。
export let store = createStore(reducer);
<Provider store={store}>
<Router history={browserHistory}>
<Route component={parent}>
</Route>
</Router>
</Provider>
class parent exteds react.Component{
render(){
return(
<child test={this.props.test}/>
)
}
}
class child exteds react.Component{
render(){
return(
<button onChange={this.props.test}/>
or
<store.dispatch(testfunction()>
)
}
}
function mapStateToProps(state) {
console.log(state)
return {...state};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
test:testfunction
}, dispatch)
};
export const renderFormGenerator = connect(mapStateToProps,mapDispatchToProps)(render);