Edit: The next version is 13.3.0
I have a state called localArray
that I want to update only to a specific index, so I thought of creating a time variable to modify the array and update the state with the time value, the problem is, this state is not updated until It doesn't update until another status update or a quick refresh, I don't know why this happens
Here is a minimal reproducible example:
import { useState } from 'react' function Test() { const [someState, setSomeState] = useState(""); const [localArray, setLocalArray] = useState(["","","",""]) const handleArrayChanges = ( { target: { name, value } } ) => { let newArray = localArray; newArray[Number(name)] = value; setLocalArray(newArray); } return ( <div> <h4>Array state</h4> <textarea name='0' onChange={handleArrayChanges}/> <p> {localArray[0]}</p> <h4>Some other state</h4> <button onClick={() => {setSomeState("a")}}>Update some other state</button> </div> ) } export default Test
As you can see, after the array state is updated, the first element should be displayed on the paragraph, but it is not displayed until the cis case is explained
P粉1063017632023-09-09 00:13:05
React is built on the assumption that state is immutable. You are mutating an existing array, not creating a new one, so after setting the state, React compares the before and after states, finds that they are the same array, and therefore thinks nothing has changed. So it won't re-render.
Instead, create a copy of the array and modify it:
const handleArrayChanges = ({ target: { name, value } }) => { let newArray = [...localArray]; // <--- creating a shallow copy newArray[Number(name)] = value; setLocalArray(newArray); };