【发布时间】: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