5

这是一个常见问题,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/>;
  }

});
4

1 回答 1

10

嘿试试这个...

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

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

于 2016-05-19T12:58:12.487 回答