首页 > 解决方案 > redux 操作成功后清除表单

问题描述

我将表单输入存储在 React componentstate中。当我提交表单时,我触发了一个 Redux 操作。当此操作成功时,我想再次更新状态 - 清除表单。但是怎么做呢?

我的意思是,我也可以轻松地将表单状态存储在 Redux 中,一切都会得到解决,但我更愿意将组件特定的东西存储在组件状态中。

标签: reactjsredux

解决方案


您应该使用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?>)

推荐阅读