【问题标题】:Optimized search bar filter in reactjsreactjs中优化的搜索栏过滤器
【发布时间】:2020-08-02 18:45:41
【问题描述】:

我已经在 reactjs 中实现了搜索过滤器,但是每当我在字符串中添加空格时,它也不会显示现有产品。 例如:我的值如下:“Iphone details”、“Samsung phone deatils”。如果我输入“Iphone”,我会得到搜索到的字符串“Iphone details”,但是如果我在“IPhone”之后点击“space”,我不会得到“Iphone details”但是将找不到任何结果。谁能帮我优化我的 react 应用搜索。

 const searchFilter = this.state.details.filter(
      (data) => {
        if (this.state.searchStr == null) return true;
        else if (
          data.name.includes(this.state.searchStr) ||
          data.title.includes(this.state.searchStr)
        ) {
          return data;
        }
      }
    );

谁能帮我解决代码的问题。

【问题讨论】:

    标签: javascript reactjs typescript search


    【解决方案1】:

    在对保存的值和用户输入的值进行比较时,最好将它们尽可能地保持在同一水平。这意味着我们可以通过一些规范化器来运行用户的搜索和项目的值。看看下面修改后的代码:

    const searchFilter = this.state.details.filter(
          (data) => {
            if (this.state.searchStr == null) return true;
            else if (
              data.name.toLowerCase().trim().includes(this.state.searchStr.trim().toLowerCase()) ||
              data.title.toLowerCase().trim().includes(this.state.searchStr.trim().toLowerCase())
            ) {
              return data;
            }
          }
        );
    

    我添加的功能是:

    .toLowerCase()
    .trim()
    

    这些函数的作用是将要搜索的搜索输入和 data.name 和 data.title 标准化为小写,并且 trim 函数会删除所有空格以便于比较。

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      相关资源
      最近更新 更多