在Redux中更新数组时如何避免突变状态

时间:2019-03-03 20:10:41

标签: javascript arrays reactjs ecmascript-6 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;

据我了解,我在这里改变状态,是否有一些快速修复方法来确保我不这样做?

1 个答案:

答案 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;