处理 react redux 应用程序中的异步错误 [英] Handling async errors in react redux application

查看:51
本文介绍了处理 react redux 应用程序中的异步错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候 Dan 发了推文

Sometime back Dan tweeted

当我看到时我会畏缩

`.then(() => dispatch(...)).catch(...)` 

在 React 项目中.如果组件在分派过程中抛出异常,您将陷入 catch 状态."

in React projects. If a component throws during dispatch, you’ll get into catch."

并说解决方案很简单.只是不要将呈现 UI 的 catch() after then() 链接起来.而是将错误处理程序作为第二个参数传递给 then().

And says the solution is so simple. Just don’t chain catch() after then() that renders UI. Instead pass error handler as second arg to then().

谁能解释一下为什么会这样.

Can someone explain why this is the case.

在我的例子中,我正在进行一个 ajax 调用,所以我假设我会进入 200 的任何内容作为服务器响应,并在内部捕获任何非 200 的内容,即来自服务器的错误.我在这里遗漏了什么吗?

In my case I am making an ajax call, so I assume I will get inside then for anything that is 200 as a server response and inside catch for anything that is not 200, i.e. error from server. Am I missing something here?

推荐答案

所以 Dan 的意思是,在 Async 请求中,你会期望成功调用导致 .then() 被调用,并且由于您在 .then()调度动作,这反过来将更新 redux 存储,从而更新 UI,所以如果有UI 更新过程中出现任何错误,.catch() 也将被调用,而您希望它仅在服务器返回错误时调用

So what Dan means is that in a Async request, you would expect the success call to result in .then() being called, and since you are dispatching an action in .then() which in turn will update the redux store and thus the UI, so if there is any error in the UI update process, .catch() will also be called and whereas you would expect it to only be called when the server returns an error

解决办法就是这样处理

.then(
function (){
    //handle success
    dispatch({...})
},
function () {
    //handle reject() and Error for Async request

})

这篇关于处理 react redux 应用程序中的异步错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆