React onClick 事件中使用 e.target.value 報錯

在使用React 16.12.0 版本的時候?qū)懥巳缦乱粋€函數(shù)

const judgeUserExist = () => {
        // 在搜索的過程中需要去判斷用戶是否存在, 需要做節(jié)流操作
        let pTime = Date.now();
        let timer:any = null;
        return function (e: any) {
            clearTimeout(timer);
            timer = null;
            let cTime = Date.now();
            if ((cTime - pTime) > 500) {
                setSearchValue(e.target.value);  
                pTime = cTime;
            } else {
                timer = setTimeout(() => {
                    setSearchValue(e.target.value);  //此處報錯 , e.target 為 null 
                }, 500)
            }            
        }
    }

使用后直接在瀏覽器中報錯,

Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.
此時點擊鏈接跳到 React 官網(wǎng)事件池中,可以看到以下有關(guān)事件池的信息,明白了,原來是 沒有加 e.persist(); 加了之后,果然不報錯了,哈哈哈

事件池

注意

此文章僅適用于 React 16 及更早版本、React Native。

Web 端的 React 17 不使用事件池。

查看更多關(guān)于 React 17 中的相關(guān)改動。

SyntheticEvent 對象會被放入池中統(tǒng)一管理。這意味著 SyntheticEvent 對象可以被復(fù)用,當所有事件處理函數(shù)被調(diào)用之后,其所有屬性都會被置空。例如,以下代碼是無效的:

function handleChange(e) {
  // This won't work because the event object gets reused.
  setTimeout(() => {
    console.log(e.target.value); // Too late!
  }, 100);
}

如果你需要在事件處理函數(shù)運行之后獲取事件對象的屬性,你需要調(diào)用 e.persist()

function handleChange(e) {
  // Prevents React from resetting its properties:
  e.persist();

  setTimeout(() => {
    console.log(e.target.value); // Works
  }, 100);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容