我正在使用@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>
);
}发布于 2022-03-09 14:47:13
您必须使用状态来了解要呈现的屏幕,当状态更改时,必须更改屏幕。
如果你不想堆叠屏幕,你可以使用重置,另一种方式你必须使用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>
);
}https://stackoverflow.com/questions/71408571
复制相似问题