UseEffect只发射某些部分



我正在努力使它在每次搜索字段更改时,useEffect中的代码都会执行。然而,只有console.log('hi')正在执行,其他代码都没有。

我不明白useEffect为什么选择性地运行代码。为什么会这样?

useEffect(() => {
console.log('hi')
const filteredMonsters = monsters.filter(monster => {
console.log('hi2')
monster.name.toLowerCase().includes(searchField.toLowerCase());
})
setMonsters(filteredMonsters);
}, [searchField])

页面加载后,我的控制台按预期读取'hi'。在搜索框中键入值后,我在控制台中看到以下内容:

hi

hi2

在搜索框中键入更多值后,我只看到:添加了hi,而没有添加hi2

您应该从过滤函数中返回一些内容,将其更改为以下内容:

useEffect(() => {
console.log('hi')
const filteredMonsters = monsters.filter(monster => {
return monster.name.toLowerCase().includes(searchField.toLowerCase());
})
setMonsters(filteredMonsters);
}, [searchField])

最新更新