这是一个常见问题,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/>;
}
});
答案 0 :(得分:6)
嘿试试这个......
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/>;
}
}
如果您需要更多说明,请告诉我......