如何保持用户登录使用Asyncstorage本地React即使我关闭应用程序?

h5qlskok  于 6个月前  发布在  React
关注(0)|答案(2)|浏览(50)

如何保持用户登录使用AsyncStorage在react native没有redux?如果你有任何源代码,请提供它

bihw5rsg

bihw5rsg1#

在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;
   }
    
}

gcuhipw9

gcuhipw92#

首先,将您的数据存储到本地存储,如下面的代码
第一个月
关闭应用程序后。每当用户再次打开应用程序时,请检查本地存储中的登录信息,如下面的代码

const login = await AsyncStorage.getItem('login');
    if (login !== null) {
      // We have data!!
      // navigate to the home or any other screen 
    }
   else{
       // navigate to the Login screen or any other screen 
}

字符串
有关模式详细信息AsyncStorage详细信息,请检查此link

相关问题