setTimeout in loop in react native

问题描述 投票:0回答:1

我正在尝试实现智能搜索的逻辑。我在onChangeText上的TextInput中使用下面的代码

 clearTimeout(this.timeout);
        this.timeout = 0
        this.timeout = this.timer(text);

在这里,我正在清理最后的timeOut并在timer方法中设置新的

timer = (searchText) => {
        const { selectedFilter } = this.state

        setTimeout(function () {
            //Hit Api
            console.log("new instance" + selectedFilter)


        }, 2000);
    }

上面的代码工作正常,但有一个问题,以前的监听器没有被清除。所以我多次获得控制台。请告诉我我做错了什么。提前致谢。

android react-native
1个回答
1
投票

您只需要返回setTimeout调用返回的值,如下所示:

timer = (searchText) => {
    const { selectedFilter } = this.state

    return setTimeout(function () {
        //Hit Api
        console.log("new instance" + selectedFilter)
    }, 2000);
}

此外,你不需要在this.timeout = 0之前做this.timeout = this.timer(text);

© www.soinside.com 2019 - 2024. All rights reserved.