在 AsyncStorage 中检查值后导出 react native stackNavigator



我有一个应用程序,一旦用户第一次打开应用程序,就会存储令牌,我需要在应用程序启动时检查该令牌并创建导航器,

方法1

const getValue = async () => {
try {
value = await AsyncStorage.getItem('token').then((value) =>{
console.log(value)
})
} catch (error) {
console.log(error.message);
}
};
if (token != undefined) {
stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
} else {
stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}

在第一种方法中,即使令牌存储在应用程序中,它也始终呈现主屏幕

第二种方法

const getValue = async () => {
try {
value = await AsyncStorage.getItem('token').then((value) =>{
if(value == null){
stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}else{
stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}
})
} catch (error) {
console.log(error.message);
}
};

这种方法抛出Cannot read property of router undefined

有没有办法让它工作?

导航.js


export const getValue = async () => {
let VALUE;
try {
await AsyncStorage.getItem('token')
.then((value) =>{
if(value == null){
VALUE = stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}else{
VALUE =  stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}
})
} catch (error) {
console.log(error.message);
}
return VALUE;
};

应用.js

import { getValue } from './layout/navigation/Navigation';
let Navigation = createAppContainer(getValue());
class App extends React.Component {
render() {
return (<Navigation/>)
}
}

创建路由

stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product,
Login : Login
}, 
{
headerMode: 'none',
initialRouteName : 'Home',  // provide initial route : app will open with Home page 
navigationOptions: {
headerVisible: false
},
})
// Export it with createAppContainer 
export default createAppContainer(stackNavigator);

将其导入您的应用程序.js并将其用作<Router/>

import Router from 'Application/navigation/routes';

现在,您可以做的是当用户登录时,将其令牌存储到AsyncStorage,然后重定向到主页。

在主页中,如果您没有从存储中获取令牌,则可以在挂载生命周期中添加令牌是否存在代码,则可以导航路由到登录屏幕。

相关内容

  • 没有找到相关文章