![](/img/trans.png)
[英]How do you render a component based on an AsyncStorage value in React Native?
[英]Render component after getting value from AsyncStorage in React Native
我的 React 组件将用户的设置存储在 AsyncStorage 中并在加载时获取它们。 存储和获取数据运行良好,但是组件在从异步 function 获取值之前渲染存在问题。 这怎么可能解决? 这是我的代码:
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;
你的构造函数太杂乱了。
初始化一个空的 state 变量并在页面加载时填充它
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>
)
}
看起来您正在尝试直接在构造函数中设置 state。 尝试这个:
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.setState({key: value})
}
}
);
}
}
这是一些文档: https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.