我的减速器是:
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;
据我了解,我在这里改变状态,是否有一些快速修复方法来确保我不这样做?
答案 0 :(得分:1)
使用findIndex
来查找activeTable
,并将新数组分配给包含新.list
对象的activeTable
:
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;