我有四个屏幕 A(主页)、B、C、D
每个屏幕都有一个函数,当屏幕onStart
出现时会被触发。或 onResume
,我是通过react-redux来实现的。
countdownToFirstScreen = () => {
this.timeOut = setTimeout(()=> {
clearTimeout(this.timeOut); // clearTimeout before navigate next screen
this.props.leaveTheScreenTime(); // change for some redux store boolean
this.props.navigation.navigate('A');
}, 9000);
}
如果用户点击 <Button />
在倒计时结束之前,我也设置了 clearTimeout。
<Button
onPress={() => {
clearTimeout(this.timeOut);
this.props.navigation.navigate('nextScreen');
}
/>
当我只是在 A、B 和 C 之间导航时,它正在工作。
当我尝试从 C 导航到 D 时出现问题。
C屏函数countdownToFirstScreen
即使我点击 <Button />
也会被触发在C屏上。
任何人都知道我的 setTimeout
发生了什么事和 clearTimeout
?
最佳答案
使用 React-Hooks 和 Functional Components ...事情变得容易多了...
empty-deps []
模拟 componentDidMount
的效果,其 cleanUp-callback 模拟 componentWillUnmount
const timerRef = useRef(null);
useEffect(() => {
timerRef.current = setTimeout(() => {
/** Your logic goes here */
}, 9000);
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
}, []);
关于javascript - clearTimeout 在 React Native 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54394949/