gpt4 book ai didi

javascript - 在 React Native 中从 AsyncStorage 获取值后渲染组件

转载 作者:行者123 更新时间:2023-12-03 07:10:40 25 4
gpt4 key购买 nike

我的 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>
)
}

关于javascript - 在 React Native 中从 AsyncStorage 获取值后渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63154057/

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