pet*_*gan 1 javascript ecmascript-6 reactjs
我想使用反应钩子过滤数组。这应该是一个相当简单的任务,但我假设它与异步更新的钩子有关,尽管这可能是错误的。
我很困惑,但已经包含了一个代码沙箱和我的代码如下:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
您需要过滤原始数据:
const test = teams_data.filter(team => {
return team.toLowerCase().includes(e.target.value.toLowerCase());
});
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/thirsty-austin-uqx8k
| 归档时间: |
|
| 查看次数: |
7042 次 |
| 最近记录: |