为什么在handleChange事件处理程序中,array.length方法总是比输入步骤慢一步?
P粉596161915
P粉596161915 2023-08-15 18:06:33
[React讨论组]
<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(() =&gt; { console.log(countriesToShow.length) },[countriesToShow]) const handleSearchChange = (event) =&gt; { setCountriesToShow(countries.filter(country =&gt; 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 &lt;= 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 &lt;= 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)
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号