【问题标题】:How to use the most updated state/value inside a 3rd party event handler?如何在 3rd 方事件处理程序中使用最新的状态/值?
【发布时间】:2021-01-10 10:05:25
【问题描述】:

鉴于类似:

function MapControl() {
  const [countries, setCountries] = useContext(CountriesContext)
  useEffect( () => {
    ThirdPartyApi.OnSelectCountry((country) => {
      setCountries([...countries, country])
    })
  })

  return (<ThirdPartyApi.Map />)
}

我遇到的问题是对setCountries 的调用无法按预期工作,因为countries 数组未从ThirdPartyApi 提供的自定义事件处理程序的上下文中更新。

什么是建模的简洁方法?我可以在事件处理程序中更新一个本地可变数组,但这不会从其他组件中获取对 countries 的任何更改,因此感觉注定会导致问题。

【问题讨论】:

    标签: javascript reactjs react-hooks react-context


    【解决方案1】:

    您可以使用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 dependenciesuseEffect(),这样您就不会在每次重新渲染时触发副作用。在这种情况下,你的副作用没有任何依赖,所以它应该是空的[]

    最后,确保在组件卸载时clean up 你的效果。在这种情况下,您需要在从 useEffect() 返回的回调中取消注册您的事件处理程序。

    【讨论】:

    • 啊,是的,我忘记了这个功能;我最终在MapControl 中创建了一个新状态,从OnSelectCountry 处理程序设置它,并有另一个依赖于我新创建的状态的useEffect 最终调用setCountries,但这看起来更干净,所以我将使用你的而是建议。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    相关资源
    最近更新 更多