【发布时间】:2015-02-19 00:15:45
【问题描述】:
我们都知道 React 文档说永远不要直接改变 this.state。我想我对状态数组和不变性有一个挥之不去的问题:
如果我有一组处于状态的对象,在以任何方式改变该数组时,我是否应该始终使用immutability helper 中的this question?
或者使用[].concat() 或[].slice() 作为回答here 和here 是否完全可以接受?
我再次问这个问题是因为[].concat() 和[].slice() 确实返回了新数组,但只返回了浅拷贝数组。如果我改变数组的一个元素,它也会改变数组的状态,违反了 Reactjs 状态的第一条规则(我一直在看太多 FMA:Brotherhood):
var arr1 = [{ name : "bill" }, { name : "chet" }];
var arr2 = arr1.slice();
// this changes both arrays
arr2[0].name = "kevin";
// check
(arr1[0].name === arr2[0].name) // => true; both are "kevin"
(arr1[0] === arr2[0]) // => true; only shallow copy
// this changes arr2 only
arr2.push({ name : "alex" });
// check again
(arr1.length === arr2.length) // => false;
(arr1[0].name === arr2[0].name) // => still true;
(arr1[0] === arr2[0]) // => still true;
我知道插件update 在覆盖shouldComponentUpdate 时最常用,但对于我正在做的事情,我不需要覆盖该功能;我只需要通过向数组中添加新元素(使用 concat 或 slice 解决)或更改现有元素的属性(使用 React.addons.update 解决)来改变数组中保持状态的对象。
TL;DR
如果不覆盖shouldComponentUpdate,我应该何时使用React.addons.update 而不是[].slice() 或[].concat() 来改变存储在状态中的对象数组?
【问题讨论】:
标签: javascript arrays reactjs