[英]Reflecting variable to View in React Native
I'm new in React native
and I know this common to ask but I've been confused on how can I reflect varible to my view text based on the AsyncStorage
variable, I've used AsyncStorage
but it returns me an error我是
React native
的新手,我知道这个问题很常见,但我对如何根据AsyncStorage
变量将变量反映到我的视图文本感到困惑,我使用AsyncStorage
但它返回了一个错误
Error: Can't find variable:username
错误:
Can't find variable:username
I have this我有这个
import React, {useContext,useState} from 'react';
import {
View,
Text,
StyleSheet,
ImageBackground,
} from 'react-native';
import {AuthContext} from '../navigation/AuthProvider';
import AsyncStorage from '@react-native-async-storage/async-storage';
const LoginScreen = ({navigation}) => {
const {googleLogin} = useContext(AuthContext);
const [state, setState] = useState(username);
AsyncStorage.getItem('userPrivilege').then((variable) => {
if (variable != null) {
console.log("hoy");
console.log(variable);
setState({username: variable})
}
});
return (
<View >
<ImageBackground source={require('../assets/images/launch_screen.png')} style= {styles.backgroundImage} >
<Text>{state.username}</Text>
</ImageBackground>
</View>
);
};
Update更新
It works now but when I tried to print value through a console it has infinite value in my console, do you know what the problem is?它现在可以工作但是当我试图通过控制台打印值时它在我的控制台中有无限的价值,你知道问题出在哪里吗?
Your error comes from an misunderstanding about how useState
works.您的错误来自对
useState
工作原理的误解。
The value from the useState
, state
in your case takes the type of what you put inside, in your case username
in a string
or undefined
at the begging .来自
useState
的值state
在您的情况下采用您放入其中的类型,在您的情况下username
为string
或undefined
在 begging 。
So state
is not an object
at the begging .所以
state
不是object
在乞讨。
To fix your error, you can initialize your state to要修复您的错误,您可以将 state 初始化为
const [state, setState] = useState({username: ''});
Update but it gets me an error更新但它给我一个错误
Objects are not valid as a React child(Found: object with keys {username}).If you meant to render a collection of children, use an array instead.
Code代码
const [state, setState] = useState({username: ''});
AsyncStorage.getItem('userPrivilege').then((variable) => {
if (variable != null) {
setState({username: variable})
}
}
return (
<View>
<Text>{state}</Text>
</View>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.