试图更改嵌套对象的属性之一。我不确定,因为我知道arrayCopy是浅拷贝,因此不会复制处于该状态的原始数组内的对象。但是,当我更改应该保留对原始元素的引用的update元素时,这是否与更改状态相同?

let arrayCopy = [...state.array]; // [ {},{}...] copy some array of nested objects
let updatedElement = arrayCopy[index]; // take some particular element
updatedElement.flag = true; // change one of its properties
return {...state, array: arrayCopy} // This is inside a reducer

最佳答案

几乎,但是您需要像其他元素一样复制要更新的对象(将flag设置为开),因此无法就地更新它:

let arrayCopy = [...state.array]; // [ {},{}...] copy some array of nested objects
let updatedElement = arrayCopy[index] = {...arrayCopy[index]}; // copy the element we're updating
// −−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−^
updatedElement.flag = true; // change one of its properties
return {...state, array: arrayCopy} // This is inside a reducer

关于javascript - 这是改变 react 状态的可接受方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61538191/

10-11 09:16