React-Native 导航使用 useEffect 和 setTimeout 跳转到错误的屏幕
React-Native navigation jumps to wrong screen with useEffect and setTimeout
我有一个包含不同屏幕的导航堆栈,我不想依次呈现这些屏幕。我将超时设置为 5 秒,因此它将转到堆栈中的下一个屏幕。
<Stack.Screen name="StoryScreenOne" component={StoryScreenOne} />
<Stack.Screen name="StoryScreenTwo" component={StoryScreenTwo} />
<Stack.Screen name="StoryScreenThree" component={StoryScreenThree} />
我的超时函数是这样的
useEffect(() => {
setTimeout(() => {
props.navigation.navigate('StoryScreenTwo');
}, 5000);
});
问题是,如果我在屏幕二并导航回屏幕一,下一个呈现的屏幕是屏幕三,而不是我想要的屏幕二。
对此有什么建议吗?
如果我知道当你到达屏幕时,还有另一个 useEffect
是这样的:
useEffect(() => {
setTimeout(() => {
props.navigation.navigate('StoryScreenThree');
}, 5000);
});
我认为 setTimeout 仍然是 运行,所以如果你想在 goBack 上重新渲染屏幕 2,你需要在按下后退按钮时使用 clearTimeOut。
看这个:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals
但是当您导航时您的第一个屏幕不会卸载,因此您需要使用侦听器重新启动 UseEffect
,就像这样:
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}
更多信息在这里:https://reactnavigation.org/docs/navigation-lifecycle/
我有一个包含不同屏幕的导航堆栈,我不想依次呈现这些屏幕。我将超时设置为 5 秒,因此它将转到堆栈中的下一个屏幕。
<Stack.Screen name="StoryScreenOne" component={StoryScreenOne} />
<Stack.Screen name="StoryScreenTwo" component={StoryScreenTwo} />
<Stack.Screen name="StoryScreenThree" component={StoryScreenThree} />
我的超时函数是这样的
useEffect(() => {
setTimeout(() => {
props.navigation.navigate('StoryScreenTwo');
}, 5000);
});
问题是,如果我在屏幕二并导航回屏幕一,下一个呈现的屏幕是屏幕三,而不是我想要的屏幕二。
对此有什么建议吗?
如果我知道当你到达屏幕时,还有另一个 useEffect
是这样的:
useEffect(() => {
setTimeout(() => {
props.navigation.navigate('StoryScreenThree');
}, 5000);
});
我认为 setTimeout 仍然是 运行,所以如果你想在 goBack 上重新渲染屏幕 2,你需要在按下后退按钮时使用 clearTimeOut。
看这个:https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals
但是当您导航时您的第一个屏幕不会卸载,因此您需要使用侦听器重新启动 UseEffect
,就像这样:
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}
更多信息在这里:https://reactnavigation.org/docs/navigation-lifecycle/