我开始与redux一起玩,到目前为止我很惊讶。我现在的问题是,我的新reducer函数更改了一个状态变量的类型,而我不希望那样。
我只想从jsons数组中删除一个对象:
pseudo:
delete state.items[item_index].jsons[json_to_delete_index]
我最终得到了这个reducer,它现在以对象而不是数组的形式返回项目状态。
case DELETE_JSON:
const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);
const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);
return {
...state,
items: {
...state.items,
[item_index]: {
...state.items[item_index],
jsons:
[
...state.items[item_index].jsons.splice(0, json_index),
...state.items[item_index].jsons.splice(json_index + 1)
]
}
}
};
到目前为止,我已经尝试了各种方法,但是在高度嵌套的对象中更改状态似乎仍然像是对redux的折磨。有人知道写方法吗?
我通过使用不可变性助手中的update()解决了这一问题。非常便利
import update from 'immutability-helper';
/* some other code */
case DELETE_JSON:
const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);
const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);
return update(state, {
items: {
[item_index]: {
jsons: {$splice: [[json_index]]}
}
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句