为什么在handleChange事件处理程序中,array.length方法总是比输入步骤慢一步?
P粉596161915
P粉596161915 2023-08-15 18:06:33
0
1
402
<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>
P粉596161915
P粉596161915

全部回复(1)
P粉765684602

当你调用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)
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板