Redux 带indexOf的减速器检查动作.type
我编写了一个redux reducer,它可以帮助我对来自其他reducer的错误消息进行分组 我想知道这是否会有任何副作用,因为我没有看到任何人这样做。我还想知道是否有更好的方法,我想不出 这是我写的:Redux 带indexOf的减速器检查动作.type,redux,react-redux,Redux,React Redux,我编写了一个redux reducer,它可以帮助我对来自其他reducer的错误消息进行分组 我想知道这是否会有任何副作用,因为我没有看到任何人这样做。我还想知道是否有更好的方法,我想不出 这是我写的: const errors = (state = {}, action = {}) => { let new_state = Object.assign({}, state); // if action type contains ERROR and action er
const errors = (state = {}, action = {}) => {
let new_state = Object.assign({}, state);
// if action type contains ERROR and action error is present
if (action.type.indexOf("ERROR") != "-1" && action.error) {
let error_id = Utils.hashCode(action.error);
// if error already in the array
if (new_state[error_id]) {
new_state[error_id].count++;
}
// otherwise add the message to the list
else {
new_state[error_id] = {message: action.error, count: 1};
}
}
// regular switch stmt
switch (action.type) {
case ERRORS_RESET: new_state = {}; break;
}
return new_state;
}
我的商店现在看起来像这样:
{
reducer1: {
something: [],
error: "Some error message",
},
reducer2: {
something: [],
error: false,
},
reducer3: {
some_other_obj: {},
error: "Another error message",
},
errors: [
{message: "Some error message, count: 1}
{message: "Another error message", count: 2}
]
}
侦听
“SOMETHING\u ERROR”
操作的总体概念是好的,但是您的实现存在一些问题
首先,您的if
语句直接改变了现有状态。根据Redux文档的一节,您需要确保复制每一层嵌套。现在,您正在复制状态的第一级,但不是嵌套对象
第二,你总是在复制状态,即使实际上没有什么变化。这通常会导致UI中出现不必要的重新渲染。谢谢!对于第一点,我仍然需要掌握它的窍门,主要是因为我编写的减缩器只需要关心平面对象。第二点是我从未想过的,它实际上很有意义。