为什么在handleChange事件处理程序中,array.length方法总是比输入步骤慢一步?
P粉596161915
2023-08-15 18:06:33
<p>我正在尝试创建一个基于输入进行过滤的列表,只有在有10个或更少的对象时才显示结果,但是array.length始终滞后于输入。</p>
<pre class="brush:php;toolbar:false;">const [countriesToShow, setCountriesToShow] = useState([])
const [newSearch, setSearch] = useState('')
const [showSearched, setShowShearched] = useState(true)
const [notificationMessage, setNotificationMessage] = useState(null)
useEffect(() => {
console.log(countriesToShow.length)
},[countriesToShow])
const handleSearchChange = (event) => {
setCountriesToShow(countries.filter(country =>
country.name.common.toLowerCase().includes(event.target.value.toLowerCase())))
setSearch(event.target.value)
if (event.target.value.trim().length === 0) {
setNotificationMessage(null)
setShowShearched(false)
}
else if (countriesToShow.length <= 10) {
setNotificationMessage(null)
setShowShearched(true)
console.log(countriesToShow.length)
}
else {
setNotificationMessage('list too long')
setShowShearched(false)
console.log(countriesToShow.length)
}
}</pre>
<p>我设法通过Effect Hook帮助正确打印出长度,但是我对如何将其实现到'else if (countriesToShow.length <= 10)'中感到困惑,因为它仍然滞后于输入。</p>
当你调用
handleSearchChange
然后调用setCountriesToShow
来更新状态时:你触发了重新渲染。新更新的状态值只会在即将到来的重新渲染中变得可用,这就是为什么它落后的原因。
如果你想在下面使用该值,你需要先将它存储在一个变量中: