我试图从AsyncStorage获得用户名(Reactive-Native)。并将此数据解析为<Text></Text>。
我的当前代码什么也不显示。
获取数据的代码
getCreds = () => {
return AsyncStorage.getItem('username')
}
...
<Text>{this.getCreds()}</Text>HomeScreen.js
存储数据的代码
export const onSignIn = (username, pswd) => {
AsyncStorage.setItem('username', username).done();
AsyncStorage.setItem('pswd', pswd).done()
}auth.js
我的问题是如何从AsyncStorage获取用户名并在呈现函数中解析为<Text></Text>?
发布于 2018-11-21 19:14:22
您的问题是,您可能会得到名为AsyncStorage.getItem的异步调用,因此在调用它时需要考虑到这一点。
就这么说吧
constructor(props) {
super(props);
this.state = {username: null};
this.loadCredentials();
}
async loadCredentials() {
try {
const username = await AsyncStorage.getItem('username');
this.setState({username: username});
}
catch (error) {
// Manage error handling
}
}
render() {
const {username} = this.state;
if (username != null) {
return <Text>{username}</Text>
}
return <Text>Loading text...</Text>
}发布于 2020-12-24 19:43:14
按照以下步骤完成
const[name,setname]=React.useState("");
const[flag,setFlag]=React.useState(false)
const getCreds = async() => {
let username= await AsyncStorage.getItem('username')
setname[username];
setFlag[true];
}
if(!flag)
{
getCreds();
}
...
<Text>{name}</Text>https://stackoverflow.com/questions/53418908
复制相似问题