我将表单输入存储在 React 组件state
中。当我提交表单时,我会触发 Redux 操作。当此操作成功时,我想再次更新状态 - 清除表单。但是怎么做呢?
我的意思是,我也可以轻松地在 Redux 中存储表单状态,一切都会得到解决,但我更愿意将特定于组件的东西存储在组件状态中。
您应该使用 redux-thunk 之类的东西来延迟调度,直到 API 调用成功:
const postForm = data => dispatch => fetch(...).then((...) => dispatch(...))
由于fetch
返回一个 Promise,因此您可以等到它被解析(api 调用成功(后再在组件中执行表单清除:
props.postForm(...)
.then(() => this.setState(<clear the form state>))
.catch(<do something to warn the user api call failed?>)
该操作究竟在状态上更新了什么?
一种方法是在组件WillReceiveProps中添加一个额外的案例来处理表单的更新。如果操作 let 比如说更新了列表,则组件中的组件 WillReceiveProps 方法上可能会有类似以下内容的内容:
componentWillReceiveProps(nextProps) {
if (nextProps.list !== this.props.list) {
this.setState({
formFields: this.getNewClearFormFields()
})
}
}
其中getNewClearFormFields是一个返回新表单字段的函数
如果您想在redux action
成功后更新state
,那么我建议您继续通过比较prevState
和nextState
将其放在componentWillReceiveProps
使用mapStateToProps()
将redux state
映射到component
然后更新组件状态,如下所示
componentWillReceiveProps(nextProps) {
this.setState({
...
});
}