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

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

问题描述

我的redux动作中有一个异步函数,它在我的reducer中返回一个这样的对象:

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 ,如果结果是成功完成然后获取:true 获取:false

所以我映射了redux状态在react-redux中使用connect的道具,我在我的组件的渲染函数中添加了这个:

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更改为error时,如何处理react组件的错误处理。我现在拥有的是:

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分配给一个错误并且它不为null,这导致它显示弹出窗口,即使没有错误。

我是否必须在每次显示时重置我的错误,或者是否有更好的做法来做这件事?

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)
));

并且,当您收到从<$ c $触发的ERROR操作时,显示您的错误弹出窗口c> redux-catch 中间件。当您关闭弹出窗口时,会调度一个将错误重置为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天全站免登陆