首页 > 解决方案 > AsyncStorage.setItem 返回 null(等待获取完成)

问题描述

通过获取,我从服务器获取 JWT。接收到这个 JWT,因为当我执行 console.log(resData.token) 时,令牌显示在控制台中。但我无法将令牌保存在异步存储中。响应是这样的:

{“_40”:0,“_55”:空,“_65”:0,“_72”:空}

我认为当 asynstorage.setItem 运行时提取还没有完成,但我怎么能等待它先完成呢?

import React, { useState } from 'react';
import { Text, TextInput, Button, SafeAreaView } from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';

const SignInScreen = props => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const SignInHandler = async () => {    
    const req = await fetch('http://localhost:8080/auth/signin', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({username: username, password: password})
    });
    const res = await req;
    if (res.ok) {
      const resData = await res.json();
      console.log(resData.token); // this works!
      await AsyncStorage.setItem('token', JSON.stringify(resData.token));
      console.log(AsyncStorage.getItem('token')); // this does not work
    } else {
      console.log('no user found');
    };
  };
  return (
    <SafeAreaView>
      <Text>Username</Text>
      <TextInput value={username} onChangeText={username => setUsername(username)} />
      <Text>Password</Text>
      <TextInput value={password} onChangeText={password => setPassword(password)} />
      <Button title="Sign In" onPress={SignInHandler} />    
    </SafeAreaView>
  );
};

SignInScreen.navigationOptions = navigation => ({
  headerShown: false
});

export default SignInScreen;

标签: jsonreact-native

解决方案


AsyncStorage 中的方法是异步的。你可以这样使用它:

console.log(await AsyncStorage.getItem('token'));

您可以在文档中找到更多信息


推荐阅读