将 AsyncStorage 数据获取到 <Text></Text>

Get AsyncStorage data to <Text></Text>

我正在尝试从 AsyncStorage (React-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>

您的问题是 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>
}

按照以下步骤完成

    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>