首页 > 解决方案 > 即使我关闭应用程序,如何使用 Asyncstorage 保持用户登录反应本机?

问题描述

如何在没有 redux 的情况下使用 AsyncStorage 在本机反应中保持用户登录?如果您有任何源代码,请提供

标签: react-native

解决方案


在 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,而不仅仅是问您想要的问题。


推荐阅读