![](/img/trans.png)
[英]Am I mutating my reducer state by replacing an entire array in an object?
[英]Changing a nested array value based on a given index in a reducer while not mutating state
我有一個減速器處理一個帶有數組的對象。 我想根據給定的索引更改嵌套數組上的值。 此代碼有效,但我似乎無法使用深度凍結使我的測試正常工作。 我試圖在這里查看 redux 示例http://redux.js.org/docs/basics/Reducers.html使用.map
來查找索引但沒有運氣。 有任何想法嗎?
export default function myReducer(state = { toDisplay: [] }, action) {
const { type, groupIndex, itemIndex } = action;
const newObject = Object.assign({}, state);
switch (type) {
case actionTypes.TOGGLE_GROUP:
newObject.toDisplay[groupIndex].isSelected = newObject.toDisplay[groupIndex].isSelected ? false : 'selected';
return newObject;
case actionTypes.TOGGLE_ITEM:
newObject.toDisplay[groupIndex].values[itemIndex].isSelected = newObject.toDisplay[groupIndex].values[itemIndex].isSelected ? false : true;
return newObject;
default:
return state;
}
}
編輯:
對於觀看有用的redux 視頻后好奇的人,我想出了這個:
export default function myReducer(state = { toDisplay: [] }, action) {
const { type, groupIndex, itemIndex } = action;
switch (type) {
case actionTypes.TOGGLE_GROUP:
return {
...state,
toDisplay: [
...state.toDisplay.slice(0, groupIndex),
{
...state.toDisplay[groupIndex],
isSelected: state.toDisplay[groupIndex].isSelected ? false : 'selected'
},
...state.toDisplay.slice(groupIndex + 1)
]
};
case actionTypes.TOGGLE_ITEM:
return {
...state,
toDisplay: [
...state.toDisplay.slice(0, groupIndex),
{
...state.toDisplay[groupIndex],
values: [
...state.toDisplay[groupIndex].values.slice(0, itemIndex),
{
...state.toDisplay[groupIndex].values[itemIndex],
isSelected: state.toDisplay[groupIndex].values[itemIndex].isSelected ? false : true
},
...state.toDisplay[groupIndex].values.slice(itemIndex + 1)
]
},
...state.toDisplay.slice(groupIndex + 1)
]
};
default:
return state;
}
}
使用建議的助手/庫可能是最好的方法,但我的團隊不希望添加其他依賴項。
首先, Object.assign(...)
只做一個淺拷貝。 見這里。
由於您將對象嵌套在嵌套在對象內部的數組中,我強烈推薦 react 中的不變性助手(如 Rafael 所述)。 這些允許你做這樣的事情:
case actionTypes.TOGGLE_GROUP:
return update(state, {
toDisplay: {
[groupIndex]: {
isSelected: {$set: newObject.toDisplay[groupIndex].isSelected ? false : 'selected'}
}
}
});
如果您想使用原始 js 修改數組中的簡單值,那么您可以使用以下內容:
return list
.slice(0,index)
.concat([list[index] + 1])
.concat(list.slice(index + 1));
( 來源)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.