繁体   English   中英

反应后执行动作

[英]perform action after time react

我正在根据用户输入更改我的 state。 像这样:

    <form>
        <input type='text' onChange={handleSearchChange} placeholder='Zoeken'></input>
    </form>

和处理程序:

const handleSearchChange = (e) => {
    setSearchKey(e.target.value.toLowerCase().trim());
}

setSearchKey 设置 state。 当用户停止输入至少 0.5 秒时,我想调用 setSearchKey function。 现在 function 在用户键入后立即被调用,但我希望用户键入并在用户键入后 0.5 秒调用集合 function。 这是否可以使用 setTimeOut,在我的情况下不确定如何实现。

首先创建一个超时参考:

const timeOut = useRef(null);

然后修改你的handleSearchChange:

const handleSearchChange = (e) => {
    clearTimeout(timeOut.current);
    timeOut.current = setTimeout(() => {
        setSearchKey(e.target.value.toLowerCase().trim());
    }, 500);
}

暂无
暂无

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

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