【问题标题】:Search Text Filtering only recognizes first input搜索文本过滤仅识别第一个输入
【发布时间】:2022-01-12 23:11:16
【问题描述】:

我的搜索栏过滤器出现问题。例如,我希望可以在我的平面列表中搜索比特币或 btc 的名称。但是,它只接收第一个(比特币),当我输入(btc)时,平面列表没有改变。我注意到通过切换变量 item.CoinInfo.FullNameitem.CoinInfo.Name 它只会选择首先列出的内容。

search = searchText => {
    this.setState({searchText: searchText});

    // searchText empty, reset filtered array
    if (!searchText) {
      this.setState({filteredCryptos: []});
      return;
    }

    let filteredCryptos = this.state.cryptos.filter(function (item) {
      // Defaults to empty string
      let name = item.CoinInfo
        ? item.CoinInfo.FullName || item.CoinInfo.Name || ''
        : '';

      // If no such property, skip
      if (!name) {
        return false;
      }

      // Change to both to lowercase, as you want to match 'bitcoin' and 'Bitcoin'
      return name.toLowerCase().includes(searchText.toLowerCase());
    });
    this.setState({filteredCryptos: filteredCryptos});
  };

【问题讨论】:

    标签: react-native search filter


    【解决方案1】:

    这就是问题

    let name = item.CoinInfo
            ? item.CoinInfo.FullName || item.CoinInfo.Name || ''
            : '';
    

    name 变量成为第一个具有真值的项目,因此只会比较您首先放置的任何项目(如果两者都不是真值,则为 '')。 您需要对FullNameName 变量进行比较。

    search = searchText => {
        this.setState({searchText: searchText});
    
        // searchText empty, reset filtered array
        if (!searchText) {
          this.setState({filteredCryptos: []});
          return;
        }
    
        let filteredCryptos = this.state.cryptos.filter(function (item) {
          // Defaults to empty string
          let {FullName, Name } = item.CoinInfo
    
          // If no such property, skip
          if (!Name && !FullName) {
            return false;
          }
          // this way gives Name (short name) precedence
          return Name.toLowerCase().includes(searchText.toLowerCase()) ||
                FullName.toLowerCase().includes(searchText.toLowerCase());
          // this way give FullName precedence
          return FullName.toLowerCase().includes(searchText.toLowerCase()) ||
                Name.toLowerCase().includes(searchText.toLowerCase()) 
        });
        this.setState({filteredCryptos: filteredCryptos});
      };
    

    通过使用 or || 运算符,如果第一个值不为真,则执行第二个,让您在需要时同时搜索FullNameName

    【讨论】:

    • 有 2 个 return 语句 - 第二个 return 语句不会到达,对吧?
    • 是的。每个返回语句都是关于优先顺序的。只需注释掉/删除你不需要的那个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多