Take a look at the following code

import {useState} from 'react' function App() { let [count, setCount] = useState(0); let [arr, setArr] = useState([]); const handleClick = () => { count += 1; SetCount (count) console.log(count)} const getCount = ()=>{setTimeout(() =>{console.log(count) // Press getCount first Const handleArrClick = ()=>{arr.push(math.random ()) // setArr(arr) React Hook Does not add items to the array. Instead, completely replace setArr([...arr]) console.log(arr)} return (<> <h2>{count}</h2> <button with a new array onClick={handleClick}>Add</button> <button onClick={getCount}>getCount</button> <br/> { arr.map((item,index)=>{ return <h2 key={index}>{item}</h2> }) } <button onClick={(e)=>handleArrClick(e)}>Add arr</button> </> ); } export default App;Copy the code

React Hook uses only the useState hook function to add state to function (stateless) components. The reason for this is the Capture Value feature;

The concept of Capture Value is explained in useEffect complete guide. “Each Render content takes a snapshot and is preserved, so when Rerender the State changes, N Render states are formed, and each Render State has its own fixed Props and State.”

The solution is available for reference

React Hooks: Get prevState values

Here are some tips for changing data:

This.setstate ({object: {... The object, the key: value}}); Array.splice (0, 1); Enclosing setState ({array}); // 3, delete array.splice(array.length-1); Enclosing setState ({array}); Array.splice (index, 1); Enclosing setState ({array}); This.setstate ({array: [...array, item]}); This.setstate ({array: [item,...array]}); Array.splice (index, 0, item); Enclosing setState ({array}); Function updateArrayItem(index, key, value) {this.setState({array: array.map((item, _index) => _index == index ? {... item, [key]: value} : item) }); } // this. SetState (prevState => return newState);Copy the code