繁体   English   中英

在 React 中更新状态后的函数调用

[英]Function call after updating the state in React

在这个结构中:

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>
    )
}

在更新counter后,从<Child>调用updateFn()的最佳方法是什么,但单击相同? 我需要这个,因为我在updateFn()使用更新计数器的值。

我已经尝试在<Child>使用useEffect ,如下所示:

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

但问题是,首先它尝试在挂载时立即调用该函数,这不好,因为计数器未更新,其次也是最重要的,我收到错误Cannot read property 'preventDefault' of undefined - 如果我注释掉了会导致刷新的preventDefault() ,这也不好。 作为一个附带问题,如何从<Child>调用它,同时保持preventDefault()行为? 如果我在 onClick 事件中调用它,没有括号()preventDefault()将起作用。

我为此找到的解决方案是:

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

虽然这是有效的,但我认为这不是一个很好的方法,我想学习正确的方法。

谢谢!

您可以在updateCounter函数中执行此操作,如下所示:

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

此外,您可以在updateCounter函数中获取onClick的事件参数并将其传递给updateFn以便能够对该事件调用preventDefault

useEffect使用counter作为依赖调用它确实会在第一次渲染时执行它。 您可以添加一个额外的状态变量来跟踪它是否是第一次点击,并根据它调用updateFn ,但对于一个简单的问题,它仍然是一个复杂的解决方案。 上面描述的解决方案应该就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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