使用钩子的输入搜索过滤器数组

时间:2019-08-29 14:46:20

标签: javascript reactjs ecmascript-6

我想使用react钩子过滤数组。这应该是一个相当简单的任务,但是我认为这与异步更新钩子有关,尽管这可能是错误的。

我很困惑,但是在下面包含了一个code sandbox和我的代码:

const teams_data = [
  "tottenham",
  "arsenal",
  "man utd",
  "liverpool",
  "chelsea",
  "west ham"
];

function App() {
  const [teams, setTeams] = React.useState(teams_data);
  const [search, setSearch] = React.useState("");

  return (
    <div className="App">
      <input
        onChange={e => {
          const test = teams.filter(team => {
            return team.toLowerCase().includes(e.target.value.toLowerCase());
          });
          console.log("test: ", test);

          // uncomment line below and teams is logged as I want
          setTeams(test);
          setSearch(e.target.value);
        }}
        type="text"
        value={search}
      />
      {teams.map(team => (
        <p>{team}</p>
      ))}
    </div>
  );
}

2 个答案:

答案 0 :(得分:2)

您需要过滤原始数据:

  const test = teams_data.filter(team => {
    return team.toLowerCase().includes(e.target.value.toLowerCase());
  });

https://codesandbox.io/s/thirsty-austin-uqx8k

答案 1 :(得分:1)

您只需要为搜索结果添加其他状态

    const [data , setData] = useState(teams);
    const [query, setQuery] = useState('')
    const[res , setRes] = useState([]);
    return (
      <div className="App container">
          <form onSubmit = {(e) => e.preventDefault()}>
              <input type = "search" className = "srh" placeholder = "search about..." 
              onChange = {(e) => {
                const test = data.filter(team => {
                  return (
                    team.toLowerCase().includes(e.target.value.toLowerCase())
                  )
                })
                setRes(test)
                if(e.target.value === '') setRes([])
              }}
              />
          </form>
          <div>
          {
            res.map((item , i) => (
            <p key = {i}>{item}</p>
            ))
          }
          </div>
      </div>
    );