Async await 响应本机等待AsyncStorage获取值

Async await 响应本机等待AsyncStorage获取值,async-await,react-native,asyncstorage,Async Await,React Native,Asyncstorage,这是一个常见的问题,在从异步存储中获取值之前尝试渲染。我在好几个地方看到了解决方案,但出于某种原因,它根本不适合我。也许是因为我用的是React Native 25.1?它只是被无限期地“加载…”卡住了。如果我在render上运行控制台日志以显示isLoading(不使用If方法),它将返回false,然后返回true,因此理论上它应该可以工作。但是如果使用if方法,它将永远处于“加载”状态,并且日志只返回false import React, { Component } from 'react

这是一个常见的问题,在从异步存储中获取值之前尝试渲染。我在好几个地方看到了解决方案,但出于某种原因,它根本不适合我。也许是因为我用的是React Native 25.1?它只是被无限期地“加载…”卡住了。如果我在render上运行控制台日志以显示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/>;
  }

});
import React,{Component}来自'React';
进口{
文本,
看法
异步存储
}从“反应本机”;
类主页扩展组件{
构造函数(道具:对象):void{
超级();
此.state={
孤岛加载:false,
};
}
组件willmount(){
AsyncStorage.getItem('accessToken')。然后((token)=>{
这是我的国家({
孤岛加载:false
});
});
}
render(){
if(此.state.isLoading){
返回装载。。。;
}
//这是您希望在承诺解决后显示的内容
返回;
}
});
嘿,试试这个

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/>;
  }
}
import React,{Component}来自'React';
进口{
文本,
看法
异步存储
}从“反应本机”;
类主页扩展组件{
构造函数(道具:对象):void{
超级(道具);
此.state={
孤岛加载:false,
};
}
组件willmount(){
AsyncStorage.getItem('accessToken')。然后((token)=>{
这是我的国家({
孤岛加载:false
});
});
}
render(){
if(此.state.isLoading){
返回装载。。。;
}
//这是您希望在承诺解决后显示的内容
返回;
}
}

如果您需要更多的澄清,请告诉我…

好的,您似乎刚刚纠正了我的输入错误,即离开“var component=React.createClass({”很明显,这不是问题所在,或者它会立即抛出错误,它一开始不会显示“加载”屏幕,更不用说太长时间了。除非你的代码中有其他内容,但据我所知,除了删除打字错误之外,它是相同的?嘿..相同的代码和react native 0.25.1在我的系统。我收到此警告:只能更新已安装或正在安装的组件。这通常意味着您对已安装的组件调用了setState、replaceState或forceUpdate。这是不可行的。@jickson您是否尝试将代码放入
componentDidMount