为什么用react钩子过滤状态数组不起作用,但是过滤原始数组却行得通 [英] why filtering state array with react hooks doesn't work but filtering original array does

查看:102
本文介绍了为什么用react钩子过滤状态数组不起作用,但是过滤原始数组却行得通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于用户的输入,我正在对数组进行过滤.如果我从状态中使用teams,它将不起作用,但是如果使用原始数组,它将正确过滤.谁能解释为什么会这样?我有点难过.

Based on an input from a user I am filtering over an array. It doesn't work if I use the teams from the state, but if I use the original array it does filter correctly. Can anyone explain why this is happening? I am a bit stumped.

此处有一个 codesandbox 供参考.

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 => {
          // if I filter on teams below it doesn't work as it should
          // but if I use teams_data (original array) it works
          const filteredTeams = teams_data.filter(team => {
             return team.toLowerCase().includes(e.target.value.toLowerCase());
          });
          setTeams(filteredTeams);
          setSearch(e.target.value);
        }}
        type="text"
        value={search}
      />
      {teams.map(team => (
        <p>{team}</p>
      ))}
    </div>
  );
}

推荐答案

如果先过滤teams,然后过滤setTeams,则只能从集合中删除团队.当开始时,您的过滤器不匹配任何内容时,它已经将您的teams减少为一个空数组.另一方面,如果您使用teams_data,则始终使您的所有团队都可以使用该过滤器.

If you filter teams and then setTeams, you can only remove teams from the collection. When at the beginning your filter does not match anything, it already reduces your teams to an empty array. If you use teams_data on the other hand you always have all your teams available to the filter.

这篇关于为什么用react钩子过滤状态数组不起作用,但是过滤原始数组却行得通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆