在 Redux 和 React 中处理错误的最佳实践 [英] Best practice to handle errors in Redux and React

查看:15
本文介绍了在 Redux 和 React 中处理错误的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 redux 操作中有一个异步函数,它在我的减速器中返回一个像这样的对象:

I have an asynchronous function in my redux actions and it returns an object like this in my reducer:

{
user: {},
fetching: false,
fetched, false,
error: null
}

所以基本上当我开始调用异步函数时,我将 redux 状态更新为 fetching: true,如果结果成功实现,则 fetched:true取:假
因此,我使用 react-redux 中的 connect 将 redux 状态映射到 props,并将其添加到组件的渲染函数中:

So basically when I start calling the asynchronous function I update the redux state to fetching: true and if the result is successfully fulfilled then fetched:true and fetching:false
So I map the redux state to props using connect in react-redux and I added this in my component's render function:

if(this.props.fetched) {
  // Go to next page
}

一旦数据被获取,它会自动进入下一页.
但是,我的错误处理有问题.当错误从 null 变为错误时,我如何处理我的反应组件上的错误处理.我现在拥有的是:

And it automatically goes to the next page once the data is fetched.
However, I have a problem with my error handling. When error changes from null to error then how do I handle the error handling on my react component. What I have right now is:

if(this.props.error != null) {
   // popup error
} 

但现在我最终遇到的情况是,下次我调用我的操作时,它已经将 this.props.error 分配给了一个错误,并且它不为空,这导致即使没有错误也会显示弹出窗口.
每次显示错误时我都必须重置它吗?或者有没有更好的做法来做这件事?

But now I end up in a situation that next time I call my action it already has this.props.error assigned to an error and its not null which results it displaying the popup even if there is no error.
Do I have to reset my error everytime it is displayed or is there any better practice of doing this whole thing?

推荐答案

您可以使用 redux-catch 中间件,用于捕获 Redux 减速器和中间件的错误.

You can use the redux-catch middleware to capture the errors for Redux reducers and middlewares.

你可以使用类似的东西,

You can use something like,

import reduxCatch from 'redux-catch';

function errorHandler(error, getState, lastAction, dispatch) {
    //dispatch ERROR action as you need.
}

const store = createStore(reducer, applyMiddleware(
  reduxCatch(errorHandler)
));

并且,当您收到由 redux-catch 中间件触发的 ERROR 操作时,显示您的错误弹出窗口.当您关闭弹出窗口时,调度一个将错误重置为 null 的操作,以便在没有要显示的错误时不会显示弹出窗口.

And, display your Error Popup when you receive the ERROR action which is triggered from the redux-catch middleware. When you close the popup, dispatch an action which resets the error to null so that popup would not be displayed if there are no errors to display.

这篇关于在 Redux 和 React 中处理错误的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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