我有:
const [list, setList] = useState([]);
在组件的某个地方,我想做:
list[index][someKey] = some_updated_value;
setList(list);
这有效吗?
或者,这样做更好吗:
const newList = list;
newList[index][someKey] = some_updated_value;
setList(newList);
如果这样更好,为什么?
我有:
const [list, setList] = useState([]);
在组件的某个地方,我想做:
list[index][someKey] = some_updated_value;
setList(list);
这有效吗?
或者,这样做更好吗:
const newList = list;
newList[index][someKey] = some_updated_value;
setList(newList);
如果这样更好,为什么?
这两种实现都将被视为状态Mutations ,应该避免,因为这在React中是反模式的.React使用浅层引用相等性判断作为其协调过程的一部分,即,如果状态块与上一个渲染周期的对象引用相同,则假定该值相同,并跳过重新渲染.
版本1
这只是直接改变状态对象.
list[index][someKey] = some_updated_value; // <-- mutation!
setList(list);
版本2
由于newList
是对list
的引用,这也会直接改变state对象.
const newList = list; // <-- newList reference to state
newList[index][someKey] = some_updated_value; // <-- mutation!
setList(newList);
React状态更新的 idea 是应用不变的更新模式.这是创建任何状态和正在更新的嵌套状态的浅拷贝的地方.这通常还与函数状态更新结合在一起,在函数状态更新中,您将回调函数传递给更新程序函数,更新程序函数被传递给要更新的前一个状态.这有助于避免过时的状态存储模块.
例子:
setList(list => list.map((item, i) => // Array.protptype.map creates new array
i === index
? { // new object reference for updated item
...item, // shallow copy previous item state
[someKey]: newValue // overwrite property being updated
}
: item
));
好doctor :