react-native - 即使我关闭应用程序,如何使用 Asyncstorage 保持用户登录反应本机?
问题描述
如何在没有 redux 的情况下使用 AsyncStorage 在本机反应中保持用户登录?如果您有任何源代码,请提供
解决方案
在 app.js 中
const MainNavigator = createStackNavigator(
{
LoginPage: {screen : LoginPageContainer, navigationOptions: { header: null } },
MiddlePage: {screen : MiddlePageContainerIndex, navigationOptions: { header: null } }
}
);
在登录页面
import { getItem } from '../../api/getItem';
componentDidMount = async() => {
let dataToken = await getItem();
//if token is available redirect to middlepage
if(dataToken !== null) {
const { navigate } = this.props.navigation;
navigate('MiddlePage');
}
}
在 getItem.js 中
import AsyncStorage from '@react-native-community/async-storage';
export const getItem = async() => {
try {
const value = await AsyncStorage.getItem('@storage_token');
if( value !== null ) {
return JSON.parse(value);
}else {
return null;
}
} catch (error) {
console.log(error);
return null;
}
}
希望能帮助到你。
另请阅读:https ://stackoverflow.com/help/how-to-ask 。当您陷入困境时需要 Stackoverflow,而不仅仅是问您想要的问题。
推荐阅读
- c# - Xamarin Forms 拒绝连接调用 WS
- php - 如何在 php 中访问 stdclass 对象
- python - Odoo 11 - 动作服务器
- spring - Spring Keycloak 身份验证 - 为 Web 应用程序和 Web 服务提供服务
- c - 如何使用 dup2 将标准输入和标准输出重定向到管道文件描述符?
- swift - SwiftUI 将 TupleView 转换为 AnyView 数组
- vue.js - 如何使用 vue-ckeditor 在 ckeditor 中使用图像上传?
- python - 如何使用内容类型等于 multipart/mixed 的 shell 脚本发送电子邮件
- vue.js - 如果 PWA 未运行或设备处于睡眠状态,则在后台运行服务
- html - 如何在反应中编辑任何发布的文本