将以下guide用于反应导航V5
我已将欢迎屏幕和主屏幕添加到堆栈导航器 我在Async Storage中有一个令牌来检查令牌的值
如果令牌为真,则导航器应显示主页 如果它为null,它将呈现欢迎屏幕
现在作为异步欢迎屏幕呈现为异步存储 每次启动该应用程序时。
let check = null
getData = async () => {
try {
const value = await AsyncStorage.getItem('@firstLaunch')
if(value !== null) {
check === value
}
} catch(e) {
// error reading value
}
}
return (
<Stack.Navigator>
{check === null ? (
// No token found, render welcome screen
<Stack.Screen
name="welcome"
component={WelcomeScreen}
}}
/>
) : (
// render HomeScreen
<Stack.Screen name="Home" component={HomeScreen} />
)}
</Stack.Navigator>
);
let check = null
getData = async () => {
try {
const value = await AsyncStorage.getItem('@firstLaunch')
if(value !== null) {
check === value
}
} catch(e) {
// error reading value
}
}
return (
<Stack.Navigator>
{check === null ? (
// No token found, render welcome screen
<Stack.Screen
name="welcome"
component={WelcomeScreen}
}}
/>
) : (
// render HomeScreen
<Stack.Screen name="Home" component={HomeScreen} />
)}
</Stack.Navigator>
);
答案 0 :(得分:0)
您可能需要一些具有效果的东西。 react-native的钩子useEffect就是这样做的。
这里有个例子:
import React from 'react'
import { Text, View, StyleSheet } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import AsyncStorage from '@react-native-community/async-storage'
const Stack = createStackNavigator()
const WelcomeScreen = () => <View style={styles.view}><Text>Welcome Screen</Text></View>
const HomeScreen = () => <View style={styles.view}><Text>Home Screen</Text></View>
export default props => {
const [token, setToken] = React.useState(null)
const [isLoaded, setLoaded] = React.useState(false)
React.useEffect(() => {
const getData = async () => {
try {
const token = await AsyncStorage.getItem('@firstLaunch')
if(token !== null)
await setToken(token)
} catch(e) {
// error reading value
}
setLoaded(true)
}
getData()
return () => null
},[])
// this is needed so you don't have that blink from Welcome to Home (When you have a token but it's not set yet in the state)
if(!isLoaded)
return null
return (
<NavigationContainer>
<Stack.Navigator>
{ token === null
? <Stack.Screen name="Welcome" component={WelcomeScreen} />
: <Stack.Screen name="Home" component={HomeScreen} />
}
</Stack.Navigator>
</NavigationContainer>
)
}
const styles = StyleSheet.create({
view: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})