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