如何使用 useState 函数组件更新对象数组中的数组

How to update an array inside an array of objects with useState function component

如何使用状态函数组件更新数组内部的数组 数组在 setTask() 内以及如何使用 setTask() 并在照片

中添加 new_photo
const new_photo = "testing2.png"; <------------ insert this value in photos

const [task, setTask] = useState([
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png"] <------------ here
    }
])

结果应该是这样的:

[
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png","testing2.png"]
    }
]
    const new_photo = "testing2.png"; // <------------ insert this value in photos

const [task, setTask] = useState([
    {
        task_id: 123,
        title: "sample",
        photos: ["testing1.png"] // <------------ here
    }
])

const arrayPush = (ID) => {
  setTask((element) => {
    element.forEach((e) => {
      if (e.task_id === ID) {
       e.photos.push(new_photo);
     }
    });
  });
console.log(task);
}

const arrayPush2 = (ID) => {
    let taskCopy = Array.from(task)
    taskCopy.forEach((element) => {
      if (element.task_id === ID) {
        element.photos.push(new_photo);
      }
    });
    setTask(taskCopy)
};

arrayPush(123)
arrayPush2(123)
setTask((oldTasks) => {
  const myTask = oldTasks.find(t => t.task_id === 123)
  return [
    ...oldTasks.filter(ot => ot.task_id != 123),
    {
      ...myTask,
      photos: [...myTask.photos, new_photo],
    }
  ]
})


参考:spread operator and asynchronous state update