如何在不按下React Native中的按钮/链接的情况下重定向到其他屏幕



我正在使用@react-navigation/native库进行导航。现在的场景是,我想在setTimeout中导航到后面的另一个屏幕。我不想堆叠页面,所以我不使用native-stack。我已经尝试了以下代码,但它没有重定向到HomeScreen

App.tsx

import React, { useEffect } from 'react';
import { Text, View } from 'react-native';
import { createNavigationContainerRef } from '@react-navigation/native';
import HomeScreen from './src/screens/HomeScreen';
const navigationRef = createNavigationContainerRef();
function navigate(name, params) {
if (navigationRef.isReady()) {
navigationRef.navigate(name, params);
}
}
export default function App() {
// after 3 seconds it should redirect to HomeScreen
useEffect(() => {
setTimeout(() => {
navigate(HomeScreen, {})
//navigate('HomeScreen', {})
}, 3000)
})
return (
<View><Text>Hello</Text></View>
);
}

您必须使用一个状态来了解要渲染的屏幕,当该状态更改时,您必须更改屏幕。

如果你不想堆叠屏幕,你可以使用重置,另一种方式是你必须使用if来决定它。例如,使用重置的第一种情况https://reactnavigation.org/docs/5.x/navigation-actions/#reset

import { CommonActions } from '@react-navigation/native';
export default function App() {
const navigation = useNavigation()
// after 3 seconds it should redirect to HomeScreen
useEffect(() => {
setTimeout(() => {
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [{ name: 'Home' }],
})
);
}, 3000)
}, [])
return (
<View><Text>Hello</Text></View>
);
}

对于第二个示例(以及正确的IMHO(

export default function App() {
const [changeScreen, setChangeScreen] = useState(false)
// after 3 seconds it should redirect to HomeScreen
useEffect(() => {
setTimeout(() => {
setChangeScreen(true)
}, 3000)
}, [])
return (
changeScreen ? 
<Home /> :
<View><Text>Hello</Text></View>
);
}

最新更新