本文介绍了反应本机间隔状态不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
状态更改中的间隔函数不起作用,请帮帮我.
interval function in state change not working help me please.
状态不变
function Home({ route, navigation }) {
const [ marker, setMarker ] = useState(0);
_stropeText = () => {
if (marker == 0){
setMarker(marker => 1);
} else {
setMarker(marker => 0);
}
}
React.useEffect(() => {
setLoading(true);
const unsubscribe = navigation.addListener('focus', () => {
setInterval(_stropeText, 500);
});
return () => { };
}, [navigation]);
}
https://snack.expo.io/Hbedd4HVh
推荐答案
你 在 marker
值上有一个闭包,将它添加到 useEffect
依赖数组,或者使用带有 useRef
钩子的引用.
You have a closure on marker
value, add it to useEffect
dependency array, or use a reference with useRef
hook.
此外,您将回调传递给 useState
,它使 功能更新,这里不是这种情况.
Also, you passing a callback to useState
, it makes functional updates, which is not the case here.
function Home({ route, navigation }) {
const [marker, setMarker] = useState(0);
React.useEffect(() => {
setLoading(true);
const _stropeText = () => {
if (marker === 0) {
setMarker(1);
} else {
setMarker(0);
}
};
const unsubscribe = navigation.addListener("focus", () => {
setInterval(_stropeText, 500);
});
return () => {
/*remove listener*/
};
}, [navigation, marker]);
}
这篇关于反应本机间隔状态不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!