【问题标题】:React Native wait for AsyncStorage to get valueReact Native 等待 AsyncStorage 获取值
【发布时间】:2016-09-16 07:53:01
【问题描述】:

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

});

【问题讨论】:

  • 您是否尝试将代码放入componentDidMount

标签: async-await react-native asyncstorage


【解决方案1】:

嘿试试这个...

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

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

【讨论】:

  • 好的,您似乎刚刚纠正了我的错字,即意外留下了“var component = React.createClass({”。显然这不是问题,否则它会立即引发错误,它不会首先显示“加载”屏幕,不要介意太久。除非您的代码中有其他内容,但据我所知,除了删除错字之外,它是相同的?
  • 嘿.. 相同的代码和 react-native 0.25.1 在我的系统中为我工作。
  • 我收到此警告:只能更新已安装或已安装的组件。这通常意味着您在未安装的组件上调用了 setState、replaceState 或 forceUpdate。这是一个无操作。 @jickson
猜你喜欢
  • 2019-03-21
  • 2021-03-26
  • 2017-04-12
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
相关资源
最近更新 更多