如何更新陣列內的陣列使用狀態函陣列件陣列在里面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"]
}
]
uj5u.com熱心網友回復:
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],
}
]
})
參考:擴展運算子和異步狀態更新
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443227.html
標籤:javascript 数组 反应式 使用状态
