indexOf方法过滤器在React中创建了意外的输出

时间:2019-01-05 22:37:54

标签: javascript html reactjs search redux

  • 我正在尝试实现类似于Google航班的过滤器。
  • 在Google航班中,当我输入m时会显示迈阿密。
  • 在我的搜索中,如果键入m,则显示美国,但应显示迈阿密。
  • 我调试了代码,发现它使用indexOf方法进行过滤。
  • 有什么办法可以过滤,以便解决问题。
  • 如果您让我知道,那就太好了,以便将来我自己修复它。
  • 提供我的代码段,在下面发布屏幕截图和沙箱

https://codesandbox.io/s/x9q44520oo

filter issue

Autocomplete.jsx

  onChange = e => {
    const { suggestions } = this.props;
    const userInput = e.currentTarget.value;

    // Filter our suggestions that don't contain the user's input
    const filteredSuggestions = suggestions.filter(
      suggestion =>
        suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
    );
    console.log("filteredSuggestions", filteredSuggestions);

    this.setState({
      activeSuggestion: 0,
      filteredSuggestions,
      showSuggestions: true,
      userInput: e.currentTarget.value
    });
  };

index.js

<Autocomplete
        suggestions={[
          "Alligator",
          "america",
          "Bask",
          "Crocodilian",
          "Death Roll",
          "california",
          "miami",
          "NEPHROLOGY",
          "PEDIATRIC NEPHROLOGY",
          "PEDIATRIC CARDIOLOGY CARDIOVASCULAR DISEASE",
          "PEDIATRIC BEHAVIOR & DEVELOPMENT",
          "PEDIATRIC INTENSIVE CARE",
          "PORTABLE X RAY",
          "PEDIATRICIAN",
          "Eggs",
          "Jaws",
          "Reptile",
          "Solitary",
          "Tail",
          "Wetlands"
        ]}
      />

1 个答案:

答案 0 :(得分:1)

如果输入出现在搜索文本(indexOf)的任何位置,

> -1将返回值suggestion。听起来您似乎只想包含以输入开头的建议-有一个.startsWith函数可以做到这一点,即:

const filteredSuggestions = suggestions.filter(
  suggestion =>
    suggestion.toLowerCase().startsWith(userInput.toLowerCase())
);