【问题标题】:Authentication in React Native with AsyncStorage使用 AsyncStorage 在 React Native 中进行身份验证
【发布时间】:2020-12-20 03:40:26
【问题描述】:

在我的项目中,当uid保存在AsyncStorage中时,表示用户已经登录。


当前代码

索引.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;
  },
};

这段代码可以运行,但我想让它更简单,就像一个函数一样。

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

【问题讨论】:

    标签: reactjs react-native jwt


    【解决方案1】:

    您会在多个地方使用它吗?为什么不在你的组件中做呢?

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

    【讨论】:

    • 是的,我将在不止一个地方使用它。
    • 你在使用像 redux 这样的全局状态管理吗?因为你可以在这里获取一次,然后在你需要的任何其他组件中从 redux 中获取值
    • 我没有使用 redux。谢谢,看起来有比我目前更好的方法。
    【解决方案2】:

    你可以在 Index.js 中使用 Promise 和 Do all Job 像

    AsyncStorage.getItem('uid').then((uid) => {
        this.setState({
            auth : (uid) ? true : false
        })
    })
    

    或者干脆使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      相关资源
      最近更新 更多