我正在构建一个应用程序,并且作为测试,我将令牌存储在钥匙串中。在导航中,我使用堆栈导航器和切换导航器。我正在尝试从钥匙串中检索令牌,并用它来确定intialRouteName:如果令牌存在->主页,如果不存在->身份验证。
这是我的代码:
Navigation.js
import React, { Component } from 'react'
import {
createStackNavigator,
createAppContainer,
createSwitchNavigator
} from 'react-navigation'
import Login from '../screens/Login'
import Register from '../screens/Register'
import Home from '../screens/Home'
import * as Keychain from 'react-native-keychain'
async function isLogged() {
const token = await Keychain.getGenericPassword()
if(token.username) {
return 'App'
}else {
return 'Auth'
}
}
const AppStack = createStackNavigator(
{
Home: {
screen: Home,
navigationOptions: {
header: null
}
},
}
)
const AuthStack = createStackNavigator(
{
Login: {
screen: Login,
navigationOptions: {
header: null
}
},
Register: {
screen: Register,
navigationOptions: {
header: null
}
}
},
{
headerLayoutPreset: 'center',
initialRouteName: 'Login'
}
)
const MainNavigator = createAppContainer(
createSwitchNavigator(
{
App: AppStack,
Auth: AuthStack
},
{
initialRouteName: isLogged()
}
)
)
export default MainNavigator
App.js
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import { persistor, store } from './src/store/createStore'
import { PersistGate } from 'redux-persist/integration/react'
import MainNavigator from './src/navigation/StackNavigation'
export default class App extends Component {
render() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<MainNavigator></MainNavigator>
</PersistGate>
</Provider>
)
}
}
不幸的是,它不起作用,导航器在获取令牌数据之前已呈现。我很难弄清楚如何获取数据并显示正确的视图。.有什么想法吗?
答案 0 :(得分:0)
您可以执行以下操作:
在所有页面的顶部创建一个组件,该组件从钥匙链中检索令牌并像这样导航:
import React, { Component } from 'react';
import {View} from 'react-native';
import{Loading} from './LoadingComponent';
import * as Keychain from 'react-native-keychain'
class TopComponent extends Component {
componentDidMount(){
//retireve your token here ...
this.setState({isLoading:false}); // set loading to false
if(token.username) {
this.props.navigation.navigate('AppStack')
}else {
this.props.navigation.navigate('AuthStack')
}
}
constructor(props) {
super(props);
this.state = {
isLoading:true,
}
}
render() {
if(this.state.isLoading == true){
return (
<Loading />
);
}else{
return(
<View></View>
);
}
}
}
export default TopComponent;
您的负载(活动指示器组件):
import React from 'react';
import {
ActivityIndicator,
StyleSheet,
Text,
View,
} from 'react-native'
const styles = StyleSheet.create({
loadingView: {
alignItems: 'center',
justifyContent: 'center',
flex: 1
},
loadingText: {
color: '#512DA8',
fontSize: 14,
fontWeight: 'bold'
}
});
export const Loading = () => {
return(
<View style={styles.loadingView} >
<ActivityIndicator size="large" color="#512DA8" />
<Text style={styles.loadingText} >Loading . . .</Text>
</View>
);
}
最后从交换机导航器中删除您的logs()函数,并在交换机导航器中添加TopComponent并将其设置为初始路由。