去抖动中的leading=true 未按预期执行

smi*_*omb 6 debouncing lodash react-native

使用 lodash 的debounce(),我等待 10 秒,然后在我的应用程序状态中设置搜索词。但我想searching在去抖之前设置应用程序的状态:

onChangeText(text) {
    setSearching(true);
    setSearchTerm(text);
}
render(){
    return(
        <TextInput style={s.input}
            onChangeText={_.debounce(this.onChangeText, 10000, {'leading':true} )}
        />
    )
}
Run Code Online (Sandbox Code Playgroud)

从文档来看,这应该在超时的前沿运行,直到事件停止指定的等待时间。实际行为就像根本没有去抖一样,事件每次在调用时都会运行,没有 10 秒的缓冲区。有任何想法吗?删除{'leading':true}确实会适当地进行去抖,但我需要在 10 秒之前在我的应用程序中设置状态。

Anu*_*ani 0

您可以在您的用户案例中指定前导 true。

debounce(func, [wait=0], [options={ leading: true}])
Run Code Online (Sandbox Code Playgroud)

请阅读链接中的文档https://lodash.com/docs#debounce

  • 看起来正确的语法是 `onChangeText={ _.debounce(this.onChangeText, 1200, {'leading':true,'trailing':false} ) }` 但这给了我一种类似于完全没有反跳的行为,这不是我需要的。 (4认同)