【问题标题】:React search onChange cancel request反应搜索 onChange 取消请求
【发布时间】:2018-06-25 07:26:04
【问题描述】:

我正在使用 Axios 处理搜索功能 onChange。它工作正常。

但问题是当用户将输入删除为空时。请求仍然发送。

我的代码。

    handleSearch = (e) => {
    const query = e.target.value;
    if(this.timeout) clearTimeout(this.timeout);

    this.timeout = setTimeout(() => {
        if (query === '') // do something ????

        requestApi.searchMultiData('search/multi', query)
            .then(response => {
                this.props.data(response.data);
            })
            .catch(error => console.log(error));
    }, 300);
    };

我该如何处理?我的解决方案是文本输入为空时。该请求应被取消。有什么想法吗?谢了。

【问题讨论】:

  • if (query !== '') { requestApi.searchMultiData('search/multi', query) ....
  • if (query === '') return(在您的声明之后)
  • 谢谢大家,它的工作。对不起我的简单问题。
  • 其实:handleSearch = (e) => { const query = e.target.value; if(this.timeout) clearTimeout(this.timeout); if (query === '') return; this.timeout = setTimeout(() => {

标签: javascript reactjs


【解决方案1】:

再看一遍,我建议这样做:

handleSearch = (e) => { 
  const query = e.target.value; 
  if (this.timeout) clearTimeout(this.timeout); 
  if (query.trim() === '') return; // here is the logical place to leave
  this.timeout = setTimeout(() => {

【讨论】:

    【解决方案2】:

    您正在寻找early exit from function 的方法。这意味着如果满足条件(query 为空:请参阅如何实现它here),您的回调函数中的部分或大部分代码将不会被执行。

    我还建议使用trim() 删除空格;否则,像 这样的值将被认为是正确的,但它们可能不是。

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 2017-08-14
      • 2019-09-14
      • 2017-08-19
      • 1970-01-01
      相关资源
      最近更新 更多