简体   繁体   中英

React.js handler function doesnt set state immediately

Simply wanted to do dynamic modal . When i click the button it works but doesnt set state immediately. First console.log returns empty array. Others work properly.

//State and handler

const [showModal, setShowModal] = React.useState([])

const handleModal = (id) => {
    const modalData = data?.filter((item) => item.id == id )
    setShowModal(modalData)
    console.log(showModal)
}

console.log(showModal)
console.log(showModal)

Ive tried useEffect like that also

useEffect(() => {

}, [showModal])

Two things you need to know about the state update in React:

  • State is updated asynchronously
  • In any particular render, state and props don't change, changes are only reflected when component re-renders

If you want to log the updated value of selected , put the log statement in the useEffect hook.

You can't update and log the updated value of any state variable in the same render; component will have to re-render to reflect changes due to state update.

Similarly, if you want to call a function with the updated value of selected , call the function from inside the useEffect hook.

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