input输入时触发ajax请求事件 在这个时候如何实现函数防抖

input输入时触发ajax请求事件 在这个时候如何实现函数防抖

    searchInput(e){
        this.setState({
            searchContent:e.target.value
        })
        fetch(`/api/book/auto-complete?query=${e.target.value}`)
        .then(res=>res.json())
        .then(res=>{
            console.log(res);
            this.setState({
                completionArr:res.keywords
            })
        })
    }
阅读 2.4k
1 个回答

加个定时器setTimeout即可

searchInput(e){
        this.setState({
            searchContent:e.target.value
        })
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            fetch(`/api/book/auto-complete?query=${e.target.value}`)
            .then(res=>res.json())
            .then(res=>{
                console.log(res);
                this.setState({
                    completionArr:res.keywords
                })
            })
        }, 500)
    }
推荐问题