我们正在使用react、react-redux和react-router。在我的一个组件中,我使用 <Route>
来自 react 路由器的组件来渲染我的表单组件之一。提交表单并创建事件后,我希望我的父组件(其中包含 <Route>
组件的组件)重新渲染,以便我的事件列表将包含添加的事件。
render() {
return (
<div>
<PublicEvents events={state.public}/>
<PrivateEvents events={state.private}/>
<Route component={Form}>
</div>
)
}
我将如何更新这些状态属性,以便在提交表单后重新呈现?我尝试将父组件和 Form 组件连接到商店并使用 mapDispatchToProps,但不确定我是否应该这样做。我的 reducer 确实获得了新事件,但我不认为它会更新我的父组件的状态。
最佳答案
React Router 是否允许您通过 Route
组件传递任意 props? React 中的一个标准范例是将 onX
回调作为 props 传递给子级,以处理父级中的状态更改/事件。
在父组件中
class Parent extends React.Component {
onFormSubmit = () => {
// update local state, here
}
render() {
return (
<div>
...
<Route component={Form} onSubmit={this.onFormSubmit}/>
</div>
)
}
}
然后在您的Form
组件中
class Form extends React.Component {
onSubmit = (data) => {
if (this.props.onSubmit) this.props.onSubmit(data)
...
}
}
另一种选择是使用像 Redux 这样的全局状态存储 - Form
组件将更新存储,并且更改将“透明地”反射(reflect)在父级中(根据 redux
运作方式的定义)
编辑:他们建议将 Prop 传递给 children 以下内容:
<Route render={(props) => <Form {...props} onSubmit={this.onSubmit}/>} />
根据:https://github.com/ReactTraining/react-router/issues/4105
关于javascript - 从路由组件更新父级的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058463/