简体   繁体   中英

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. 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:

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 compares the previous state and the new state, then decides to is there a need to re-render the component. And React uses referential equality. 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.

So, you should keep creating a new instance like the following..

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

    setText('');
};

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