2020年12月21日星期一

How to set 2 states asynchronously in React using useState

I have this function:

const [numbers, setNumbers] = useState([]);  const [rows, setRows] = useState([]);    const addRow = () => {      setNumbers([...numbers, numbers.length+1]);      setRows([...rows,          <NewGradeRow key={numbers[numbers.length-1]} number={numbers[numbers.length-1]}/>]);  }  

that is supposed to add new rows. It should be adding a new value to the numbers hook, then using the new value in the numbers hook to add a new row in the rows hook. It runs synchronously though and the new row doesn't use the new value given to the numbers hook. How would I fix this?

https://stackoverflow.com/questions/65401979/how-to-set-2-states-asynchronously-in-react-using-usestate December 22, 2020 at 09:00AM

没有评论:

发表评论