react-native - 如何保持用户登录状态(使用 AsyncStorage 存储 userId)

标签 react-native authentication store asyncstorage

我可以使用我的用户名和密码(硬编码)登录,但是,登录后我想从 API 中获取一些数据,这只有在我通过身份验证后才能完成。 那么问题来了,如何让用户保持登录状态呢?

我不太擅长 React-Native,所以任何帮助将不胜感激!

这是我的代码:

import React, { Component } from 'react';
import { Text, View, StyleSheet,AsyncStorage, FlatList, AppRegistry } from 'react-native';
import { ListItem } from 'react-native-elements';


export default class BMPServer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       username: 'testuser', 
       password: 'mypasswordhere',
       signedIn: false,
      checkedSignIn: false 
      };


    this.getAllDocuments();

 }
getAllDocuments = () => {

  fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              username : this.state.username,
              password : this.state.password,
            })
          }) 

        .then((response) => response.json())

      .then((responseDocs) => {

        console.log("YOU HAVE SUCCSFULLY LOGGED IN:", responseDocs) 

});}

最佳答案

假设您在身份验证成功后获得了 token 。

    import { AsyncStorage } from 'react-native';

    fetch('https://example.dk/rest/Login/Authenticate/?businessId=1&solutionId=1', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              username : this.state.username,
              password : this.state.password,
            })
          }) 

        .then((response) => AsyncStorage.setItem(LOGIN_TOKEN, response))

      .then((responseDocs) => {

        console.log("YOU HAVE SUCCSFULLY LOGGED IN:", responseDocs) 

     });}

所以,现在您已将 token 存储在 asyncstorage 中。因此,例如,在您的初始屏幕上,启动屏幕给出一个条件来检查是否使用

AsyncStorage.getItem(LOGIN_TOKEN);

关于react-native - 如何保持用户登录状态(使用 AsyncStorage 存储 userId),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908211/

相关文章:

javascript - 如何在书签调用之间存储对象?

react-native - React native 导航堆栈导航器 header 未固定在 Web 顶部

javascript - react native 中 componentDidMount 和 componentDidUpdate 有什么区别

java - 如何在不同的浏览器页面管理多个账户的登录和注销?

authentication - 如何在 Sails js 中创建基于路由的安全策略?

vue.js - Vuex 商店自动更新

javascript - Sencha 触摸 2 : Populating one DataView using multiple stores

reactjs - React-native:多色 TextView

ios - 为什么我不能在 iOS 上离开键盘以在 React Native App 中发送 Post?

php - 将 PHP 网站与 Wordpress 用户身份验证集成