Liz*_*Liz 5 reactjs redux react-redux
我不确定如何在Redux Reducer中处理错误。当我的API提取返回数据时,我需要转换其结构并检查是否在结果数据上设置了各种属性。但是,我不能在reducer中抛出错误,因为redux至少需要返回以前的状态。我该如何处理呢?
注意:我正在使用react-redux-toastr来处理错误,并可以访问组件和操作函数中的错误分派器。
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]
};
}
Run Code Online (Sandbox Code Playgroud)
连接ObjectSearch组件后,我确实尝试在ObjectSearch reducer中更新商店的烤面包片:
reducers / index.js:
const rootReducer = combineReducers({
toastr: toastrReducer,
ObjectSearch
});
Run Code Online (Sandbox Code Playgroud)
组件/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
};
})
Run Code Online (Sandbox Code Playgroud)
但是,将以下内容添加到reducers / object-search.js:似乎是更新ObjectSearch.toastrs而不是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);
Run Code Online (Sandbox Code Playgroud)
我是react / redux新手,因此在此对应用程序结构的任何帮助将不胜感激!
小智 5
通常的模式是返回一个指示发生错误的状态。例如,在TODO APP的上下文中,如果收到的操作不正确,那么您可以输入以下内容:
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 }
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,无论监听商店的所有订户,看到返回的新状态都可以采取措施。
我认为重要的是,一切都必须是声明性的,在化简器逻辑中,您要声明状态相对于所接收动作的行为。与外部世界/上下文无关(据说该函数是纯函数)。引发错误或在外部调用某些东西会破坏模式。
有趣的是,您可以让中间件监视具有非空错误键的状态,并对此采取措施。
您可能会着迷的另一件事是,您的操作中确实存在错误:对象的形状是意外的,或者您使用的是字符串而不是错误等。在这种情况下,您可能会抛出意外的错误。会发生什么 ?
您可以在源代码中看到redux不会做任何事情。它将简单地重置为其notDispatching状态。因此,如果您不更改状态,那么一切仍然可以(无论如何都可以)。如果您这样做了,那么您手上的状态就会变得不稳定。
| 归档时间: |
|
| 查看次数: |
5551 次 |
| 最近记录: |