我正在创建一个启动屏幕组件,我想在应用程序首次启动至少5秒后运行该组件,然后显示另一个组件/屏幕。
我昨天刚开始使用react native,所以我仍然不知道如何在不引起错误的情况下完成这样复杂的事情。我设法让它在应用程序打开后出现,但它只显示了一瞬间。
这是我的代码:
App.js
const App = () => {
const [isFirstLaunch, setIsFirstLaunch] = React.useState(null);
useEffect(() => {
AsyncStorage.getItem('alreadyLaunched').then(value => {
if(value == null){
AsyncStorage.setItem('alreadyLaunched','true');
setIsFirstLaunch(true);
}else{
setIsFirstLaunch(false);
}
})
},[]);
if (isFirstLaunch == null){
return (
<SplashScreen/>
)
}else if(isFirstLaunch == true){
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Dashboard">
<WelcomeStack.Screen name="Welcome" component={WelcomeScreen}/>
<WelcomeStack.Screen name="Login" component={LoginScreen}/>
</Drawer.Navigator>
</NavigationContainer>
)
}else{
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Dashboard">
<Drawer.Screen name="Dashboard" component={LandingScreen} options={{ swipeEnabled:false
}} />
</Drawer.Navigator>
</NavigationContainer>
)
}
};
export default App;
SplashScreen.js
const SplashScreen = () => {
return (
<View style={styles.container}>
<View style={styles.header}>
<Image source ={require('../assets/Dilmune-logo1.png')}
style={styles.logo}
resizeMode="stretch"
/>
</View>
</View>
);
};
export default SplashScreen;
试试
const [showSplash, setShowSplash] = useState(true);
useEffect(() => {
AsyncStorage.getItem('alreadyLaunched').then(value => {
if(value == null){
setTimeout(() => {
setShowSplash(false)
},5000)
AsyncStorage.setItem('alreadyLaunched','true');
setIsFirstLaunch(true);
}else{
setIsFirstLaunch(false);
}
})
},[]);
if (isFirstLaunch == null && showSplash){
return (
<SplashScreen/>
)
} add
您的App
组件可能需要这样的东西:
useEffect(()=>{
const timeout = useTimeout(()=> setShowSplash(false),5000)
return () => clearTimeout(timeout)
}, [])
然后,您相应地渲染splash或应用程序。