P粉7656846022023-08-16 09:53:17
当你调用handleSearchChange
然后调用setCountriesToShow
来更新状态时:
setCountriesToShow( countries.filter(country => country .name .common .toLowerCase() .includes(event.target.value.toLowerCase()) ) )
你触发了重新渲染。新更新的状态值只会在即将到来的重新渲染中变得可用,这就是为什么它落后的原因。
如果你想在下面使用该值,你需要先将它存储在一个变量中:
const handleSearchChange = (event) => { const newCountriesToShow = countries.filter(country => country .name .common .toLowerCase() .includes(event.target.value.toLowerCase()) ) setCountriesToShow(newCountriesToShow) setSearch(event.target.value) if (event.target.value.trim().length === 0) { setNotificationMessage(null) setShowShearched(false) } else if (newCountriesToShow.length <= 10) { setNotificationMessage(null) setShowShearched(true) } else { setNotificationMessage('list too long') setShowShearched(false) } }