gpt4 book ai didi

async-await - React Native 等待 AsyncStorage 获取值

转载 作者:行者123 更新时间:2023-12-01 09:51:13 26 4
gpt4 key购买 nike

这是一个常见问题,React Native 试图在从 AsyncStorage 获取值之前进行渲染。我已经在几个地方看到了解决方案,但由于某种原因,它对我来说根本不起作用。也许是因为我使用的是 React Native 25.1?它只是无限期地卡在“正在加载...”上。如果我在渲染上运行控制台日志以显示 isLoading(没有 if 方法),它将返回 false然后 true所以理论上它应该可以工作。但是使用 if方法使其永远停留在“加载”上,并且日志仅返回错误。

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

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

关于async-await - React Native 等待 AsyncStorage 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37323132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com