使用AsyncStorage在React Native中进行身份验证

时间:2020-09-01 02:49:05

标签: reactjs react-native jwt

在我的项目中,将uid保存在AsyncStorage中时,意味着用户已经登录。


当前代码

Index.js

import React from 'react';
import Auth from 'app/src/common/Auth';
import { Text } from 'react-native';

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     auth: true,
    };
  }

  async componentDidMount() {
    await this.setState({ auth: await Auth.user() });
  }

  render() {
   const { auth } = this.state;
     return (
       {!auth ? (
         <Text>You need to Log In!</Text>
       ) : (
         <Text>You are Logged In!</Text>
       )}
     )
  }
}

Auth.js

import { AsyncStorage } from 'react-native';

export default {
  async user() {
    let result = true;
    const response = await AsyncStorage.getItem('uid');
    if (!response) {
      result = false;
    }
    return result;
  },
};

此代码有效,但我想像一个函数一样使它更简单。

如果您能给我任何建议,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您要在多个地点使用它吗?为什么不只是在您的组件中做呢?

  async componentDidMount() {
    const auth = await AsyncStorage.getItem('uid');
    this.setState({ auth });
  }

答案 1 :(得分:0)

您可以像在

中那样使用诺言并在Index.js中完成所有工作
AsyncStorage.getItem('uid').then((uid) => {
    this.setState({
        auth : (uid) ? true : false
    })
})

或简单地使用

const uid = await AsyncStorage.getItem('uid');
this.setState({ auth : (uid) ? true : false  });