基于来自用户的输入,我正在过滤一个数组。如果我使用teams
来自状态的它不起作用,但如果我使用原始数组,它会正确过滤。谁能解释为什么会这样?我有点难住了。
这里有一个codeandbox供参考。
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>
);
}