我的问题与 redux 相关,更具体地说与如何处理 reducer 函数中的错误/故障有关。我指的是 ngrx 示例应用程序 ( https://github.com/ngrx/example-app ) 及其处理错误/失败的方式。
这是我所指的减速器功能:
export function reducer(state = initialState, action: collection.Actions): State {
switch (action.type) {
case collection.ActionTypes.LOAD: {
return Object.assign({}, state, {
loading: true
});
}
case collection.ActionTypes.LOAD_SUCCESS: {
const books = action.payload;
return {
loaded: true,
loading: false,
ids: books.map(book => book.id)
};
}
case collection.ActionTypes.ADD_BOOK_SUCCESS:
case collection.ActionTypes.REMOVE_BOOK_FAIL: {
const book = action.payload;
if (state.ids.indexOf(book.id) > -1) {
return state;
}
return Object.assign({}, state, {
ids: [ ...state.ids, book.id ]
});
}
case collection.ActionTypes.REMOVE_BOOK_SUCCESS:
case collection.ActionTypes.ADD_BOOK_FAIL: {
const book = action.payload;
return Object.assign({}, state, {
ids: state.ids.filter(id => id !== book.id)
});
}
default: {
return state;
}
}
}
有人可以解释从 reducer 函数中处理这两个动作的必要性吗:
REMOVE_BOOK_FAIL
ADD_BOOK_FAIL
例如,为什么要从状态中删除这本书(在ADD_BOOK_FAIL
动作的情况下)?
如果添加图书操作失败,则该图书不在商店中。是吗?