json - 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;
解决方案
推荐阅读
- json - 如何从Angular中的JSON字符串获取数据进出打字稿接口
- css - 在 React-Boostrap 中使用容器时,我的身体的背景颜色被覆盖
- wcf - WCF 流响应返回垃圾字符
- c# - 从 Blazor 组件读取数据
- python - 如果我在打印后添加冒号,为什么解释器不会抛出错误?
- protocol-buffers - sigsegv 在原始消息上使用 MessageDifferencer
- ios - 由于编译器抛出“关联类型的模糊推断”,因此无法在 swift 中将关联类型用作方法 returnType
- javascript - 使用同一表单中选择列表的结果填充表单中的一个字段
- perl - 如何从 Perl 中的哈希中获取最小值键
- asp.net-mvc - (ASP.NET MVC) JSON 响应包装,打印未处理的异常 - PageSpeed API 请求