【问题标题】:Leading=true in debounce not performing as expected去抖动中的Leading = true未按预期执行
【发布时间】:2019-03-01 12:03:45
【问题描述】:

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

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

From the docs,这应该在超时的前沿运行,直到事件在分配的等待时间内停止。 实际行为就好像根本没有去抖动,事件在每次调用时都会运行,因为它们没有 10 秒的缓冲区。有什么想法吗? 删除 {'leading':true} 确实可以适当地进行去抖动,但我需要在 10 秒之前在我的应用中设置状态。

【问题讨论】:

  • 我也有同样的问题。看起来像 lodash 中的错误?
  • @Operator 我不确定我做了什么来解决这个问题。我知道'leading' 在我当前的项目中不在引号中,它正在工作。

标签: react-native lodash debouncing


【解决方案1】:

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

debounce(func, [wait=0], [options={ leading: true}])

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

【讨论】:

  • onChangeText={ _.debounce(this.onChangeText, 1200, [options={leading:true,trailing:true}]) } 与默认行为相同。
  • 看起来正确的语法是onChangeText={ _.debounce(this.onChangeText, 1200, {'leading':true,'trailing':false} ) },但这给了我一个类似于没有反跳的行为,这不是我需要的。
【解决方案2】:

看看这种方法是否有帮助:

debouncedSetSearchTerm = _.debounce(text => setSearchTerm(text), 10000)

onChangeText(text) {
    setSearching(true);
    debouncedSetSearchTerm(text);
}
render() {
    return(
        <TextInput style={s.input} onChangeText={onChangeText} />
    )
}

您将首先setSearching,然后调用debouncedFn,然后在10000 延迟后处理searchTerm

【讨论】:

  • TypeError: Expected a function
  • 我在本地测试过这个,所以我很确定它可以工作。无论如何,这种方法在这里更为重要......只需使用_.debounce() 的内容,但这是他们设置状态然后去抖动的方法。
  • 我正在尝试这个解决方案,它确实首先设置了状态,但对延迟后输入的每个字母执行一个 ajax 调用
【解决方案3】:

文档说,谁会再次偶然发现这个问题:

注意:如果前导和尾随选项为真,则仅当在等待超时期间多次调用去抖动函数时,才会在超时后沿调用 func。

因此,您可能需要使用{ leading: true, trailing: false } 来获得所需的内容,因为默认情况下尾随为真。

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2017-12-15
    • 2011-02-25
    相关资源
    最近更新 更多