繁体   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