根据用户的输入,我正在过滤一个数组。如果我使用的话它不起作用teams
来自状态,但如果我使用原始数组,它会正确过滤。谁能解释为什么会发生这种情况?我有点难住了。
有一个代码沙箱 https://codesandbox.io/s/immutable-dream-hwtg3在此供参考。
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
另一方面,您始终可以过滤所有团队。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)