Reactjs 为什么array.push不能触发重新呈现UI,而array.concat可以?

Reactjs 为什么array.push不能触发重新呈现UI,而array.concat可以?,reactjs,rendering,Reactjs,Rendering,我希望根据数组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 &am

我希望根据数组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]);
}
const[a,setA]=useState([];
...
函数更新(newValue){
//使用push方法将新元素附加到
a、 推送(newValue);
刚毛(a);
//使用concat创建包含新元素的新数组(&N)
刚毛([].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()
返回一个包含连接元素的新数组,甚至不涉及原始数组。它是一个浅拷贝

push()

Array.prototype.push()

如果您使用的是ES6,则可以使用spread操作符

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

   or

   setA([...a, newValue])
}
const[a,setA]=useState([];
...
函数更新(newValue){
刚毛([].concat(a,[newValue]);
或
setA([…a,新值])
}

@doannx如果答案对您有帮助,请接受/投票支持。