Problem Description:
const [data, setData] = useState([]);
data.push(1);
setData(data);
When I modify the origin array data and set it back, the page won’t refresh.
Analysis:
In vue and react, if you update a mutable object, it will cause the view to be updated. However, vue and react use shallow listening by default, which only listens to the first layer of data, and does not listen to changes in the inner layer of data. That is, the reference address of the object has not changed, just modify the content of the object, and will not cause the view to be updated.
Solution:
Make a deep copy of the original array, then modify the new array. Then pass in the modified new array, which will cause the view to update.
const [data, setData] = useState([]);
nData = data.concat();
nData.push(1);
setData(nData);
0 Comments