简体   繁体   中英

Function call after updating the state in React

In this structure:

export const Parent = () => {

    function updateFn(e) {
        e.preventDefault()
        // do some action with the updated counter
    }

    return (
        <Child updateFn={updateFn} />
    )
}

export const Child = (props) => {
    const [counter, setCounter] = useState(0)

    function updateCounter() {
        setCounter(1)
    }

    return (
        <button onClick={updateCounter}></button>
    )
}

what would be the best way to call updateFn() from within the <Child> , after the counter was updated, but with the same click? I need this because I am using the value of the updated counter in the updateFn() .

I have tried with a useEffect in the <Child> like this:

    useEffect(() => {
        props.updateFn()
    }, [counter])

but the problem with this is, first that it tries to call the function immediately on mount, which is not good because the counter is not updated, and second and most importantly, I get an error Cannot read property 'preventDefault' of undefined - if I comment out preventDefault() that will cause a refresh and that's also not good. As a side question, how can I call this from within the <Child> but also keep the preventDefault() behavior? If I would call this at the onClick event, without the brackets () , preventDefault() will work.

The solution that I found for this is to:

<div onMouseOver={() => setCounter(1)}>
    <button onClick={props.updateFn} />
</div>

While this is working, I think that this is not a very good approach, and I would like to learn the right way.

Thanks!

You can do that inside the updateCounter function as follow:

function updateCounter(e) {
  setCounter(1);
  props.updateFn(e);
}

Additionally, you can get the event paramter of the onClick in the updateCounter function and pass it to updateFn to be able to call preventDefault on that event.

Calling it in the useEffect with counter as a dependency will indeed excecute it on the first render. You could add an additional state variable to track if it is the first click or not and call updateFn depending on that, but it is still a complex solution for a simple problem. The solution described above should be enough.

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