簡體   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