【问题标题】:Handling AJAX Errors with Redux Form使用 Redux 表单处理 AJAX 错误
【发布时间】:2018-03-25 04:03:11
【问题描述】:

我是 React/Redux 的新手,所以我正在使用 Redux Form 构建一个简单的博客应用程序来帮助我学习。现在,我不清楚在我的操作中将数据从表单提交到 api 时如何处理 ajax 错误。主要问题是我正在使用 Redux Form 的 onSubmitSuccess 配置属性,它似乎总是被调用,即使发生错误也是如此。我真的不清楚是什么触发了 onSubmitSuccess 或 onSubmitFail。我的 onSubmitFail 函数永远不会执行,但我的 onSubmitSuccess 函数总是会执行,无论是否发生错误。

我在 redux-form 文档中读到了 SubmissionError,但它说它的目的是“区分由于验证错误而导致的承诺拒绝和由于 AJAX I/O 而导致的承诺拒绝”。所以,这听起来与我需要的相反。

如果这有什么不同的话,我会使用 redux-promise 作为 Redux 的中间件。

这是我的代码。我故意在我的服务器 api 中抛出一个错误以在我的 createPost 操作中生成错误:

带有我的 redux 表单的容器

PostsNew = reduxForm({
  validate,
  form: 'PostsNewForm',
  onSubmit(values, dispatch, props) {
    // calling my createPost action when the form is submitted.
    // should I catch the error here?
    // if so, what would I do to stop onSubmitSuccess from executing?
    props.createPost(values)
  }
  onSubmitSuccess(result, dispatch, props) {
    // this is always called, even when an exeption occurs in createPost()
  },
  onSubmitFail(errors, dispatch) {
    // this function is never called
  }
})(PostsNew)

onSubmit 调用的操作

export async function createPost(values) {
  try {
    const response = await axios.post('/api/posts', values)
    return {
      type: CREATE_POST,
      payload: response
    }
  } catch (err) {
    // what would I do here that would trigger onSubmitFail(),
    // or stop onSubmitSuccess() from executing?
  }
}

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    在您的情况下,redux-form 不知道表单提交是否成功,因为您没有从 onSubmit 函数返回 Promise。

    在您的情况下,无需使用 redux-promise 或任何其他异步处理库即可实现此目的:

    PostsNew = reduxForm({
      validate,
      form: 'PostsNewForm',
      onSubmit(values, dispatch, props) {
        // as axios returns a Promise, we are good here
        return axios.post('/api/posts', values);
      }
      onSubmitSuccess(result, dispatch, props) {
        // if request was succeeded(axios will resolve Promise), that function will be called
        // and we can dispatch success action
        dispatch({
          type: CREATE_POST,
          payload: response
        })
      },
      onSubmitFail(errors, dispatch) {
        // if request was failed(axios will reject Promise), we will reach that function
        // and could dispatch failure action
        dispatch({
          type: CREATE_POST_FAILURE,
          payload: errors
        })
      }
    })(PostsNew)
    

    【讨论】:

    • 这很好用。出于某种原因,我认为像 ajax 调用这样的事情应该只在你的操作内部处理。我没有考虑在我的 onSubmit 函数中这样做。
    【解决方案2】:

    要处理异步操作,您应该使用redux-thunkredux-saga 或其他可以运行异步代码的中间件。

    【讨论】:

    • 我知道使用中间件是处理异步操作的最佳方法。不知道你有没有注意到我说我在我的问题中使用了 redux-promise 中间件?我可以改用 redux-thunk,但我的问题是我不知道在使用这个中间件时如何处理错误。我不知道什么会取消我用 redux-form 配置的 onSubmitSuccess 函数,或者什么会触发 onSubmitFail 。问题是关于如何专门处理 redux-form 的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2014-03-23
    • 2017-12-24
    • 2015-03-15
    • 2019-10-20
    相关资源
    最近更新 更多