[英]How to avoid mutating state when updating array in redux
我的減速器是:
case TOGGLE_TABLE:
const newState = { ...state };
const activeTable = newState.list.find((table: any) => table.id === action.id);
if (activeTable.visible === undefined) activeTable.visible = false;
else delete activeTable.visible;
return newState;
據我了解,我在這里改變狀態,是否有一些快速解決方法來確保我不這樣做?
使用findIndex
來查找activeTable
,然后為包含新activeTable
對象的.list
分配一個新數組:
const newState = { ...state };
const { list } = newState;
const activeTableIndex = list.findIndex((table) => table.id === action.id);
const newActiveTable = { ...list[activeTableIndex] };
if (newActiveTable.visible === undefined) newActiveTable.visible = false;
else delete newActiveTable.visible;
newState.list = [...list.slice(0, activeTableIndex), newActiveTable, list.slice(activeTableIndex + 1)];
return newState;
或者,如果匹配的id
永遠不止一個,則您可以考慮.map
更為優雅:
const newState = { ...state };
const newList = newState.list.map((table) => {
if (table.id !== action.id) return table;
const newActiveTable = { ...table };
if (newActiveTable.visible === undefined) newActiveTable.visible = false;
else delete newActiveTable.visible;
return newActiveTable;
});
newState.list = newList;
return newState;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.