如何在第 3 方事件处理程序中使用最新的 state/value?
How to use the most updated state/value inside a 3rd party event handler?
给出类似的东西:
function MapControl() {
const [countries, setCountries] = useContext(CountriesContext)
useEffect( () => {
ThirdPartyApi.OnSelectCountry((country) => {
setCountries([...countries, country])
})
})
return (<ThirdPartyApi.Map />)
}
我遇到的问题是对 setCountries
的调用没有按预期工作,因为 countries
数组未根据 [=14= 提供的自定义事件处理程序的上下文进行更新].
对此建模的简洁方法是什么?可能只有一个我在事件处理程序中更新的本地可变数组,但这不会从其他组件中获取对 countries
的任何更改,因此感觉注定会导致问题。
您可以使用 functional update 使用最新值修改您的状态,而不是从陈旧的闭包中捕获它:
function MapControl() {
const [countries, setCountries] = useContext(CountriesContext)
useEffect( () => {
ThirdPartyApi.OnSelectCountry((country) => {
setCountries((prev) => [...prev, country])
})
return () => {
// unregister event handler
}
}, [])
return (
<ThirdPartyApi.Map />
)
}
同时确保 specify your dependencies 为 useEffect()
,这样您就不会在每次重新渲染时触发副作用。在这种情况下,您的副作用没有任何依赖项,因此它应该为空 []
.
最后,确保 clean up 在组件卸载时效果。在这种情况下,您需要在 useEffect()
.
返回的回调中注销您的事件处理程序
给出类似的东西:
function MapControl() {
const [countries, setCountries] = useContext(CountriesContext)
useEffect( () => {
ThirdPartyApi.OnSelectCountry((country) => {
setCountries([...countries, country])
})
})
return (<ThirdPartyApi.Map />)
}
我遇到的问题是对 setCountries
的调用没有按预期工作,因为 countries
数组未根据 [=14= 提供的自定义事件处理程序的上下文进行更新].
对此建模的简洁方法是什么?可能只有一个我在事件处理程序中更新的本地可变数组,但这不会从其他组件中获取对 countries
的任何更改,因此感觉注定会导致问题。
您可以使用 functional update 使用最新值修改您的状态,而不是从陈旧的闭包中捕获它:
function MapControl() {
const [countries, setCountries] = useContext(CountriesContext)
useEffect( () => {
ThirdPartyApi.OnSelectCountry((country) => {
setCountries((prev) => [...prev, country])
})
return () => {
// unregister event handler
}
}, [])
return (
<ThirdPartyApi.Map />
)
}
同时确保 specify your dependencies 为 useEffect()
,这样您就不会在每次重新渲染时触发副作用。在这种情况下,您的副作用没有任何依赖项,因此它应该为空 []
.
最后,确保 clean up 在组件卸载时效果。在这种情况下,您需要在 useEffect()
.