简体   繁体   中英

How do I get updated state after useEffect has set an onChange event to an element?

I have an input field that needs an onChange event to be bound on mounting the component. The onChange event needs to update the state. However, the state never gets updated because the onChange event always has the initial state. What is the best way to make this work?

Here is my code:

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

    useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])
}

You can tweek your useEffect to get the updated state. State setting is async in nature. -

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

  useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])

    useEffect(() => {
        console.log(count) //updated value//
    }, [count]) // adding count to dependency array will cause this  useEffect to run on every count change //
}

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