我有以下狀態
const state = {
courses: [],
series: [],
course: {
title: 'testing',
course_notes: [
{
id: 1,
note: "one" // want to edit this
},
{
id: 2,
note: "two"
}
]
}
}
我想改變 state.course.course_notesp[0].name
我從來沒有完全理解這是如何作業的,閱讀了很多教程,我覺得我知道它是如何作業的,但它總是讓我絆倒。這就是我正在嘗試的
const m = {
...state,
course: {
course_notes:[
...state.course.course_notes,
state.course.course_notes.find(n => n.id === 1).note = "edited"
]
}
}
這似乎添加edited為一個額外的節點。state.course.course_notes.length最終成為3.
uj5u.com熱心網友回復:
您對陣列使用擴展運算子,就像對物件一樣。
假設你有一個物件
const obj = { a: 1, b: 2 }
如果你說:
{...obj, a: 2}
你說的是:
{ a: 1, b: 2, a: 2 }
該屬性a定義了兩次,但第二個覆寫了第一個。
但是,如果對陣列執行類似的操作,結果將有所不同:
const arr = [1, 2];
const newArr = [...arr, arr[0]];
// here the result would be [1, 2, 1]
這就是為什么當你說:
course_notes:[
...state.course.course_notes,
state.course.course_notes.find(n => n.id === 1).note = "edited"
]
它的作用是向陣列添加一個額外的元素。
您應該做的是創建陣列的修改版本,例如使用 map
course_notes: state.course.course_notes.map(el => {
if (el.id === 1) {
el.note = 'edited';
}
return el;
});
uj5u.com熱心網友回復:
有很多方法可以修改商店的狀態以更新 course_notes 的一個元素。
如果我們假設 id 是唯一的,我將映射修改 id 為 1 的元素的前一個陣列。
....
course_notes: state.course.course_notes.map(x => x === 1
? { ...x, note: 'edited' }
: x
)
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369757.html
標籤:javascript 还原
