Javascript react中的setTimeout函数导致类型错误
我有一个附加了句柄函数的表单 句柄函数有一个超时,这会导致一些问题Javascript react中的setTimeout函数导致类型错误,javascript,reactjs,Javascript,Reactjs,我有一个附加了句柄函数的表单 句柄函数有一个超时,这会导致一些问题 const timeOut = useRef(null); const handleSearchChange = (e) => { // setSearchKey(e.target.value.toLowerCase().trim()); clearTimeout(timeOut.current); timeOut.current = setTimeout(() =&g
const timeOut = useRef(null);
const handleSearchChange = (e) => {
// setSearchKey(e.target.value.toLowerCase().trim());
clearTimeout(timeOut.current);
timeOut.current = setTimeout(() => {
setSearchKey(e.target.value.toLowerCase().trim());
}, 500);
}
如果我将console.log(e.target.value)放在settimeout函数之外,它就可以正常工作,当我合并settimeout函数时,它就会中断。为什么会这样
我尝试将函数简化为:
const handleSearchChange = (e) => {
// setSearchKey(e.target.value.toLowerCase().trim());
console.log(e.target.value)
setTimeout(() => {
// setSearchKey(e.target.value.toLowerCase().trim());
console.log(e.target.value)
}, 500);
}
问题仍然存在。它记录第一个console.log,在第二个中断。事件值由react清除。您需要使用event.persist来分配事件值,或者存储事件中的值以供以后使用 根据:
SyntheticEvent
对象将被重用,所有属性都将被删除
在调用事件回调后为null。这是给你的
性能原因。因此,您无法在事件中访问事件
异步方式
这是因为react中的
e
事件对象是react生成的合成事件对象,而不是内部浏览器生成的本机事件对象
为了防止一直分配新对象,它被设计为可重用对象,这意味着它的属性在发射后被剥离,并重新分配给下一个事件
对于您的情况,因为您在发出后在异步回调中重新访问了该对象,所以它被“回收”,使其属性过时。要解决此问题,可以在同步事件循环中预先保存所需的值,然后将其传递给异步回调
handleSearchChange = (e) => {
const value = e.target.value.toLowerCase().trim()
clearTimeout(timeOut.current);
timeOut.current = setTimeout(() => {
setSearchKey(value);
}, 500);
}
太棒了,我不知道这个。谢谢:)哦,看来我有点晚了:P
handleSearchChange = (e) => {
const value = e.target.value.toLowerCase().trim()
clearTimeout(timeOut.current);
timeOut.current = setTimeout(() => {
setSearchKey(value);
}, 500);
}