在使用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
targeton 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);
}