【问题标题】:Clear form after redux action succeedsredux 操作成功后清除表单
【发布时间】:2018-06-03 04:05:15
【问题描述】:

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

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

【问题讨论】:

  • 您想在触发操作后立即更新状态吗?
  • 不,我认为最好等到操作成功@MuraliPrasanth
  • 如果前一个状态和下一个状态不同,那就继续把它放在componentWillReceiveProps中。

标签: reactjs redux


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    该操作对状态的确切更新是什么?

    一种方法是在您的 componentWillReceiveProps 中添加一个额外的案例来处理表单的更新。如果操作更新列表,您可以在组件内的 componentWillReceiveProps 方法上使用类似以下内容:

    componentWillReceiveProps(nextProps) {
      if (nextProps.list !== this.props.list) {
        this.setState({
          formFields: this.getNewClearFormFields()
        })
      }
    }

    getNewClearFormFields 是一个返回新表单字段的函数

    【讨论】:

      【解决方案3】:

      如果您想在redux action 成功后更新state,那么我建议您通过比较prevStatenextState 将其放入componentWillReceiveProps

      使用mapStateToProps()redux state 映射到component 然后像下面这样更新组件状态

       componentWillReceiveProps(nextProps) {
          this.setState({
            ...
          });
        }
      

      【讨论】:

      • 这仅在受影响的 redux 状态连接到组件时才有效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多