我不确定如何在redux reducer中处理错误。当我的API获取数据时,我需要转换其结构并检查所得数据上已设置各种属性。然而,在reducer中无法抛出错误,因为redux要求至少返回先前的状态。我该如何处理这个问题?
注:我正在使用react-redux-toastr来处理错误,并且在组件和操作函数中可以访问错误分发器。
然而,将以下内容添加到reducers/object-search.js似乎更新了ObjectSearch.toastrs而不是toastr.toastrs :(
注:我正在使用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]
};
}
我尝试在ObjectSearch组件连接后,在ObjectSearch reducer中更新toastr store的部分:
reducers/index.js:
const rootReducer = combineReducers({
toastr: toastrReducer,
ObjectSearch
});
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 :(
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 新手,因此在应用程序结构方面需要任何帮助,将不胜感激!