简体   繁体   English

如何停止变异 state?

[英]How to stop mutating state?

This is the first time I've encountered mutability.这是我第一次遇到可变性。 I have state items - an object with keys that go as id, through allIds I find all id items that need to change the date, but they change all items at once, apparently this is due to mutability and I don't know how to fix it... I will really appreciate the help!我有 state 项 - 一个 object,其键为 go 作为 id,通过 allIds 我找到所有需要更改日期的 id 项,但它们一次更改所有项,显然这是由于可变性,我不知道如何修复它...我将非常感谢您的帮助!

const allIds = getSubTasksId(Object.values(state.items), payload.id);
allIds.forEach((id) => (state.items[id].date.current = payload.date));
return {
  ...state,
  items: { ...state.items },
};

Your state.items[id].date.current = payload.date statement is responsible for mutation.您的state.items[id].date.current = payload.date语句负责突变。 One of the possible solution.可能的解决方案之一。

const updatedItems = {};
allIds.forEach((id)=> updatedItems[id] = payload.date);
return {
    ...state,
    items: updatedItems
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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