AsyncStorage.setItem返回null(等待获取完成)

问题描述 投票:0回答:1

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

{“ _ 40”:0,“ _55”:null,“ _65”:0,“ _72”:null}

我认为当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;
json react-native
1个回答
0
投票

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

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

您可以找到更多信息here in the doc

© www.soinside.com 2019 - 2024. All rights reserved.