簡體   English   中英

在Redux中更新數組時如何避免突變狀態

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM