简体   繁体   English

如何将新项目添加到对象数组

[英]how can I add new item to objects array

const data = [
  {
    title: 'Todo',
    items: ['do home work', 'complete study'],
  },
  {
    title: 'In-Progress',
    items: ['learn tailwind', 'build some projects'],
  },
  {
    title: 'Completed',
    items: ['completed work'],
  },
];



const [list, setList] = useState(data);

const [text, setText] = useState('');

This addItem function adding a new copy of Todo every time when I add an item.每次添加项目时,此 addItem 函数都会添加 Todo 的新副本。 How can I add the item to the todo without adding a new copy如何在不添加新副本的情况下将项目添加到待办事项

const addItem = () => {
    setList((prev) => {
      return [
        (prev[0] = {
          ...prev[0],
          items: [text, ...prev[0].items],
        }),
        ...prev,
      ];
    });

    setText('');
};

enter image description here在此处输入图片说明

This is some problematic design choice since you assuming your todos object is always first item in the array ( prev[0] ), but going straight forward is:这是一些有问题的设计选择,因为您假设您的 todos 对象始终是数组中的第一项( prev[0] ),但直接向前是:

const addItem = () => {
  setList((prev) => {
    const [todoData, ...rest] = prev;
    return [{ ...todoData, items: [...todoData.items, text] }, ...rest];
  });

  setText("");
};

You need to create a new object, this is how react works.您需要创建一个新对象,这就是 react 的工作原理。

React compares the previous state and the new state, then decides to is there a need to re-render the component. React 比较之前的状态和新的状态,然后决定是否需要重新渲染组件。 And React uses referential equality. React 使用引用相等。 If you just keep using the same object by modifying it, then React will think that no need to re-render the component because of the state object is always the same.如果你只是通过修改来继续使用同一个对象,那么 React 会认为不需要重新渲染组件,因为状态对象总是相同的。

So, you should keep creating a new instance like the following..所以,你应该继续创建一个新的实例,如下所示..

const addItem = (item) => {
    setList((prev) => {
      return {
      ...prev,
      item
      }
    });

    setText('');
};

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

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