Redux 如何处理 reducer 中的错误 [英] Redux how to handle errors in reducer

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

问题描述

我不确定如何处理 redux reducer 中的错误.当我的 API fetch 返回数据时,我需要转换其结构并检查已在结果数据上设置的各种属性.但是,我不能在 reducer 中抛出错误,因为 redux 至少需要返回先前的状态.我该如何处理?

I'm unsure how to handle errors in a redux reducer. When my API fetch returns data, I need to transform its structure and check various properties have been set on the resulting data. However, I cannot throw errors in the reducer as redux requires at least the previous state to be returned. How do I go about handling this?

注意:我正在使用 react-redux-toastr 处理错误,并可以访问组件和动作函数中的错误调度程序.

Note: I'm using react-redux-toastr to handle errors, and have access to the error dispatcher in the component and action functions.

reducers/object-search.js:

reducers/object-search.js:

case "FETCH_OBJECTS_FULFILLED": {
  // munge data into expected format

  const _allObjects = [];
  const data = action.payload;

  // if can't find the surveys property
  if (!data.hasOwnProperty("surveys")) {

    // - - How do I handle this within the reducer? - - 

    // this.handleAlert("error", "ERROR", " Cannot find a list of surveys. Please contact support.");
    return {
      ...state,
      fetching: false
    }
  }

  // transform data (omitted for brevity's sake)

  return {
    ...state,
    fetching: false,
    fetched: true,
    options: _allObjects,
    surveys: data.surveys.map(survey => survey.name)
    // toastrs: [newToastr, ...state.toastrs]
  };

}

在连接 ObjectSearch 组件后,我确实尝试更新 ObjectSearch 减速器中存储的 toastr 切片:

I did attempt to update the toastr's slice of the store in the ObjectSearch reducer after connecting in the ObjectSearch Component:

reducers/index.js:

reducers/index.js:

 const rootReducer = combineReducers({
    toastr: toastrReducer,
    ObjectSearch 
 });

组件/对象-search.js

components/object-search.js

@connect(store => {
  return {
     fetching: store.ObjectSearch.fetching,
     fetched: store.ObjectSearch.fetched,
     ready: store.ObjectSearch.ready,
     surveys: store.ObjectSearch.surveys,
     toastrs: store.toastr.toastrs
   };
 })

但是,将以下内容添加到 reducers/object-search.js:似乎更新 ObjectSearch.toastrs 而不是 toastr.toastrs :(

however, adding the following to reducers/object-search.js: seems to update ObjectSearch.toastrs rather than toastr.toastrs :(

  const toastrs = [...state.toastr];
  const newToastr = {
     id: guid(),
     type: 'light',
     title: 'OBJECT SEARCH ERROR',
     message: 'No Data. Please contact support.',
     options: {
       ...REDUX_TOASTR_OPTIONS,
       icon: icons.ERROR_ICON,
       status: 'error'
     }
   };
  toastrs.push(newToastr);

我是一个 react/redux 新手,因此对于应用程序结构的任何帮助将不胜感激!

I'm a react/redux newbie, so any help on app structure here would be appreciated!

推荐答案

一般的模式是返回一个指示发生错误的状态.例如,在 TODO 应用程序的上下文中,如果接收到的操作不正确,那么您可以使用以下内容:

A general pattern would be to return a state indicating that an error occurred. For instance, in the context of a TODO APP if the received action is incorrect then you can have something like :

function reducer (state = { todos: [], error: null }, action) {

   switch (action.type) {

       case "ADD_TODO":
           if (typeof action.todo === "string") {

                return Object.assign({}, state, {
                    error: {
                        code: "INVALID TODO ACTION",
                        message: "The todo action received was empty, need a .text property",
                        action
                    }
                 });

           } else {

               return { todos: [action.text, ...state.todos], error: null }

           }

   }

}

然后,无论订阅者正在收听商店,看到返回的新状态都可以采取行动.

Then whatever subscriber listening to the store, upon seeing the new state returned can take action.

我认为重要的是一切都非常具有声明性,在reducer逻辑中,您声明状态相对于接收到的动作的行为.与外部世界/上下文没有关系(函数被称为纯函数).抛出错误或调用外部的东西会破坏模式.

I think what's important is that everything is very declarative, in the reducer logic you declare the behavior of the state relative to the received action. There is no relation to the outside world / context (the function is said to be pure). Throwing an error, or calling something outside breaks the pattern.

有趣的是,您可以让中间件监视具有非空错误键的状态并对此采取行动.

What's interesting in this is that you can have a middleware watching for states with non-null error key and take action on this.

您可能会担心的另一件事是当您的操作中存在真正的错误时:对象的形状出乎意料,或者您有一个字符串而不是错误等......在这种情况下,您可能会遇到意外抛出错误.会发生什么?

Another thing you may be preoccupied with is when there is a genuine error in your actions : the shape of the object is unexpected, or you have a string instead of an error etc... In this case you may have an unexpected error thrown. What will happen ?

您可以在 source 中看到 redux什么都不做.它将简单地重置为 notDispatching 状态.因此,如果您没有 mutate state 一切都还可以(无论如何都可以).如果你这样做了,那么你手上的状态就会不稳定......

You can see in the source that redux does not do anything. It will simply reset into its notDispatching state. So if you did not mutate state everything is still ok (as much as it can be anyways). If you did then you have an inconstitent state on your hands...

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

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