【问题标题】:Debouncing search input onChangeText()去抖动搜索输入 onChangeText()
【发布时间】:2019-03-01 11:10:23
【问题描述】:

使用 lodash 的 debounce(),我试图等待 1.2 秒,然后在我的应用程序状态中设置搜索词。但是当我使用它时它似乎没有运行我的功能:

onChangeText(text) {
    console.log('setting');
    setSearching(true);
    setSearchTerm(text);
}
render(){
    return(
        <TextInput style={s.input}
            onChangeText={() => {
                _.debounce(this.onChangeText, 1200);
                /*
                doing just...
                this.onChangeText(text)
                ...works
                */
            }}
        />
    )
}

使用debounce 时,我的控制台日志中没有setting。有什么想法吗?

【问题讨论】:

    标签: react-native lodash debouncing


    【解决方案1】:

    现在,您正在为处理程序的每次调用创建一个 debounce 的新实例。

    理想情况下,您应该将整个处理程序包装在 debounce 中,因为 debounce 会创建一个延迟调用 funcdebounced 函数

    onChangeText={_.debounce(this.onChangeText, 1200)}
    

    【讨论】:

    • 这行得通,但我怎么能在去抖之前打电话给setSearching(true);
    • 不确定,但您可能需要在函数内使用debounce 仅用于setSearchTerm 函数_.debounce(() =&gt; searchTerm(text), 1200)
    猜你喜欢
    • 2021-08-16
    • 2018-05-15
    • 1970-01-01
    • 2013-03-10
    • 2020-03-19
    • 1970-01-01
    • 2019-12-14
    • 2016-07-17
    • 1970-01-01
    相关资源
    最近更新 更多