繁体   English   中英

反应陈旧 state useCallback

[英]React stale state useCallback

我在我的功能组件中使用geolocation API ,我的geolocation.watchPosition(success, error)successerror回调有条件代码,该代码依赖于将要更改的某些 state 值。

我不想在useEffect内的 mount 上启动geolocation.watchPosition

我尝试使用useCallback包装回调并将 state 值传递给依赖项数组,但回调仍然关闭陈旧的 state 值,即使它已更新。 有什么解决方法吗?

简化示例:

 function Map() {
    const watchRef = useRef();
    const [isBool, setIsBool] = useState(false);
  
    function init() {
      watchRef.current = navigator.geolocation.watchPosition(success, error);
    }
  
    const success = useCallback((pos) => {
      if(isBool) {
        // do something...
        return;
      }
      // do something else...
    }, [isBool])
  
    function updateStateHandler() {
      setIsBool(true);
    }

    return // jsx...  
}

想出了一个使用refs来突破闭包的解决方案。

解决方案:

 function Map() {
    const watchRef = useRef();
    const isBoolRef = useRef(); // create a ref
    const [isBool, setIsBool] = useState(false);   

    function init() {
      watchRef.current = navigator.geolocation.watchPosition(success, error);
    }

    // no need for useCallback
    const success = (pos) => { 
      if(isBoolRef.current) {
        // do something...
        return;
      }
      // do something else...
    }
  
    function updateStateHandler() {
      setIsBool(true);
    }

    useEffect(() => {
      isBoolRef.current = isBool; // this will return the updated value inside the callback
    }, [isBool])

    return // jsx...  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM