搜尋

首頁  >  問答  >  主體

為什麼在handleChange事件處理程序中,array.length方法總是比輸入步驟慢一步?

<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粉596161915P粉596161915467 天前385

全部回覆(1)我來回復

  • P粉765684602

    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)
      }
    }

    回覆
    0
  • 取消回覆