简体   繁体   中英

How to avoid mutating state when updating array in redux

My reducer is:

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;

To my understanding, I am mutating state here, is there some quick fix to make sure I don't?

Use findIndex to find the activeTable instead, and assign a new array to the .list which contains a new activeTable object:

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;

Or, if there will never be more than one matching id , you might consider .map to be more elegant:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM