javascript - 从 React Native 中的 AsyncStorage 获取值后渲染组件
问题描述
我的 React 组件将用户的设置存储在 AsyncStorage 中并在加载时获取它们。存储和获取数据效果很好,但是组件在从异步函数获取值之前呈现的问题。这怎么可能解决?这是我的代码:
import React from 'react';
import { View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import { Media } from '../constants';
class SettingsScreen extends React.Component {
constructor(props) {
super(props);
const settings = ['appLanguage', 'colorTheme'];
for(const i of settings) {
this.getData(i).then(
value => {
if(value === null || value === undefined) {
this.state[i] = Media.initalSettings[i];
}
else {
this.state[i] = value;
}
}
);
}
}
async storeData(key, value) {
try {
if(key[0] != '@') {
key = '@' + key;
}
await AsyncStorage.setItem(key, value);
}
catch(e) {
console.warn(e);
}
}
async getData(key) {
try {
if(key[0] != '@') {
key = '@' + key;
}
const value = await AsyncStorage.getItem(key);
return value;
}
catch(e) {
console.warn(e);
}
}
render() {
const { appLanguage } = this.state;
return (
<>
<View>
{appLanguage}
</View>
</>
)
}
}
export default SettingsScreen;
解决方案
你的构造函数太混乱了。
初始化一个空状态变量并在页面加载时填充它
constructor(props){
super(props)
this.state = {
storedValue = ""
}
}
async componentDidMount() {
const storedValue = await AsyncStorage.getItem("settings");
this.setState({storedValue})
}
render(){
return (
<View>
<Text>{storedValue}</Text>
</View>
)
}
推荐阅读
- google-cloud-platform - 为什么我的 webapp.sh 没有运行并且磁盘没有附加到我的 GCP 实例?
- pandas - 具有最大总和值的类别列的熊猫组数据框
- python - 不存在这样的文件或目录来自服务器请求的错误
- python - 如何使用 Python openCV 仅在这张表格的图像中找到左上角框的位置(x、y、宽度、高度)?
- azure - 使用 Azure 防火墙的随机连接断开 - 没有可观察到的模式
- python - 如何更改我的 requests.get() 函数的发送方式?
- php - 我的网站总是内存不足(致命错误)
- vue.js - 在 bootstrap-vue 中折叠时如何隐藏导航栏
- python - 在 Python 中使用过滤器从文本文件中过滤行
- swift - 核心数据:ID 已设置,但保存时显示为 nil