The problem that data cannot be updated in time due to asynchronous use of useState

I believe that everyone has stepped on such a pit when using hooks. The data cannot be updated in time due to asynchronous useState.

const [kwd, setkwd] = useState("")

const changekwd = (res) => {
    setkwd(res.kwd)
    getNew()        //渲染数据方法
  }

As in the above example, when using setkwd to modify kwd and re-render the data, it is found that the updated data cannot be obtained immediately, and the effect is that the page data is successfully rendered only after the method is triggered twice.

This is obviously caused by the asynchrony of useState.

solution:

Use useEffect to monitor the data of useState, and use and render the data after monitoring changes (data changes).

  const [kwd, setkwd] = useState("")

  const changekwd = (res) => {
    setkwd(res.kwd)
  }

  useEffect(()=>{
    getNew()        //这里会获取到变化后的数据
  },[kwd])

I hope this article will help you ^_^

Guess you like

Origin blog.csdn.net/qq_58174484/article/details/125552137