为什么 array.push 不能触发重新渲染 UI,而 array.concat 可以?



我想根据数组 a 的值重新呈现我的 UI,如下所示:

const [a, setA] = useState([<sample_data>];
...
function update(newValue) {
// use push method to append the new element into a
a.push(newValue);
setA(a);
// use concat to create new array that includes a & new element
setA([].concat(a,[newValue]);
}

如果我使用 push,则不会触发重新渲染,但使用 concat 可以。
这对我来说很奇怪,数组 a 在这两种情况下都确实发生了变化,为什么只有 concat 触发重新渲染?

setA 使用oldValue === newValue进行检查

function setA(newValue) {
const same = oldValue === newValue;
if (!same) {
update(...);
}
}

在推送情况下,您传递的是相同的数组

a.push(..)
setA(a);
same = a === a  // true

Concat 创建一个新数组,您传入该数组

setA(a.concat(...))
same = a === newArray  // false

注意 您可以使用点差运算符

setA([...a, newValue]);

它显然比 concat 快得多

两者的工作方式不同。

康卡特((

Array.prototype.concat()返回一个带有串联元素的新数组,甚至不接触原始数组。这是一个浅层的副本。

推((

Array.prototype.push()将一个元素添加到原始数组中,并返回一个整数,该整数是其新的数组长度。

如果您使用的是 ES6,则可以使用 spread 运算符

const [a, setA] = useState([<sample_data>];
...
function update(newValue) {
setA([].concat(a,[newValue]);
or
setA([...a, newValue])
}

最新更新