【问题标题】:AsyncStorage.setItem returns null (await fetch to finish)AsyncStorage.setItem 返回 null(等待获取完成)
【发布时间】:2020-04-01 23:48:24
【问题描述】:

通过提取,我从服务器获取 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;

【问题讨论】:

  • 您无法立即从异步函数中获取值。你应该使用 Promise 等待答案,最简单的一种是 async/await 模式。

标签: json react-native


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    {"_40": 0, "_55": null, "_65": 0, "_72": null}

    这意味着承诺没有解决。 异步存储在 promise 中返回我们必须解决的值。

    尝试使用 async - await 函数来解决此问题。

    await AsyncStorage.setItem('token', JSON.stringify(resData.token)); console.log(await AsyncStorage.getItem('token'));

    这将解决问题

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2013-03-22
      • 2016-09-10
      相关资源
      最近更新 更多