React Native等待AsyncStorage获取值

Has*_*sen 3 async-await react-native asyncstorage

这是一个常见问题,React Native尝试在从AsyncStorage获取值之前进行渲染.我已经在几个地方看到了解决方案,但由于某些原因它对我来说根本不起作用.也许是因为我使用的是React Native 25.1?它只会无限期地停留在"正在加载..."上.如果我在渲染上运行控制台登录以显示isLoading(没有if方法)它返回false,然后true理论上它应该工作.但是通过该if方法使其永久停留在"正在加载"并且日志仅返回false.

import React, { Component } from 'react';

import {
  Text,
  View,
  AsyncStorage
} from 'react-native';

  class MainPage extends Component {
   constructor(props: Object): void {
   super();
   this.state = {
     isLoading: false,
   };
 }

  componentWillMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  }

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }

});
Run Code Online (Sandbox Code Playgroud)

Jic*_*son 7

嘿试试这个......

import React, { Component } from 'react';

import {
  Text,
  View,
  AsyncStorage
} from 'react-native';

class MainPage extends Component {

   constructor(props: Object): void {
       super(props);
       this.state = {
         isLoading: false,
       };
   }

  componentWillMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  }

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更多说明,请告诉我......