简体   繁体   中英

Push into an array useState React

I hope you are fine, I want to add an element to my array, how can i do that? Look at my code:

  const [datesState, setDisabledData] = useState([
    format(new Date(2021, 4, 1), "dd/MM/yyyy"),
    format(new Date(2021, 4, 4), "dd/MM/yyyy")
  ]);

  useEffect(() => {
      setDisabledData(oldArray => [...oldArray, format(new Date(2021, 4, 9), "dd/MM/yyyy")]);
  }, []);

But it doesn't works..

Nothing is wrong with your code per se, but if you put a console.log immediately after your setDisabledData, then since setting state is asynchronous, and console.log() is a synchronous function, the console.log finishes execution before the setDisabledData does, therefore printing the old state information.

The setState method for class based components has the same problem, but it has a callback function that will be called after state is set, and can be used to wait for state update to finish.

In functional components, you need to use the useEffectHook to wait for the state update.

You can refer to Wait for state to update when using hooks for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM