AsyncStorage.getItem 使用 fetch 时返回 undefined - React-Native

AsyncStorage.getItem returning undefined when using fetch - React-Native

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

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);
});
};