[英]React stale state useCallback
我在我的功能组件中使用geolocation API
,我的geolocation.watchPosition(success, error)
的success
和error
回调有条件代码,该代码依赖于将要更改的某些 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.