The problem of array push

Code:

this.state={
    data:[]
}
this.arr=[]
this.setState({
     data:this.state.data.push(ele)    //push
})

this.arr.push(ele)    //

although push returns the length of the new array, this.arr can use push, and this.state.data can only use cancat, instead of cancat,.

Apr.09,2021

in the rendering mechanism of React, directly modifying the state value cannot trigger re-rendering, but can only be performed by calling setState. This method is an asynchronous method, which puts the changes into a queue. React will merge all changes in this queue to determine whether the state has changed, thus deciding whether to re-render.

for array type state, such as data. here React states that all states contained in state should be immutable objects. This makes it easy to determine whether the state has changed-just to determine whether the reference is the same. The concat method of the array is to create a whole new array, and React thinks that state.data has changed.


setState is used to update State, and you push to update data (in fact, this is not allowed, because you can only update data with setState).

try this

this.setState({
    data:[...this.state.data,ele]//setState
})
The return value of

this.state.data.push (ele) is the array length. Change the data data type to a number. If you execute this method again, you will get an error


even if your push is successful, it will not cause the view update. You need to return a new reference

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3ed35-2c437.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3ed35-2c437.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?