javascript - 使用 fetch 时 AsyncStorage.getItem 返回未定义 - React-Native

标签 javascript react-native async-await fetch asyncstorage

我正在尝试使用 promise 和 AsyncStorage 在我的 SignIn 组件中设置一个 token ,但是当我去检索用于不同组件的 token 时,我收到错误消息 Cannot read property 'getItem' of undefined。我尝试使用 Async/Await 等待 token 响应以便将其保存到存储中,但我遇到了同样的错误。如何正确设置 token ?

SignIn.js 组件

//Function is bound
async signIn() {
const data = JSON.stringify({username: this.state.username, password: this.state.password})

  await fetch(`https://somesecretdomain.com:8443/users/login`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: data
}).then((response) => response.json()).then(async(responseJson) => { 
  AsyncStorage.setItem('jwt', responseJson.id_token);

  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({routeName: 'Profile'})]
  });
  this
    .props
    .navigation
    .dispatch(resetAction);
}).catch((error) => {
  console.warn(error);
})
};

Profile.js 组件

async fetchData() {
AsyncStorage
  .getItem('jwt')
  .then((value) => {
    this.setState({"TOKEN": value});
  })
  .done();

console.log(this.state.TOKEN)
const response = await 
fetch(`https://somesecretdomain.com:8443/users/getUsers`, {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'token': this.state.TOKEN
  }
})
const json = await response.json()

我将 Profile.js 组件更改为以下,仍然出现相同的错误。

import React, {AsyncStorage, localStorage} from 'react';
import {
Text,
View,
Image,
TouchableHighlight,
WebView,
TextInput,
KeyboardAvoidingView,
ScrollView
} from 'react-native';

 async fetchData() {
 const TOKEN = await AsyncStorage.getItem('jwt');
 const response = await 
 fetch(`https://somedomain.com:8443/users/getUsers`, {
 method: 'GET',
 headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'token' : TOKEN
},
});
const result = await response.json();
  this.setState({data: result})
}

最佳答案

试试这个:

async signIn() {
    const data = JSON.stringify({username: this.state.username, password: this.state.password})

  const response = await fetch(`https://somesecretdomain.com:8443/users/login`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: data
  });
  const result = await response.json();
  await AsyncStorage.setItem('jwt', result.id_token);

  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({routeName: 'Profile'})]
  });
  this
    .props
    .navigation
    .dispatch(resetAction);
});
};

关于javascript - 使用 fetch 时 AsyncStorage.getItem 返回未定义 - React-Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46303245/

相关文章:

javascript - 中断驱动与事件驱动 I/O 模型

javascript - Angular Js。如何修复错误 : $resource:badcfg Response does not match configured parameter

javascript - 如何使用 JQuery 删除动态表的特定行

javascript - 替换数组值

react-native - 找出 React Native 项目中未使用的导入

java - 将 Android CameraX 桥接到 React Native

react-native - 默认情况下,react-navigation v3 中标题后退按钮不起作用

c# - 等待 DbContext 时 WPF UI 阻塞

c# - Task.Run 在这里是否合适,包装网络调用?

xamarin.forms - 按下返回按钮时如何提示退出?