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

时间:2017-09-19 14:35:53

标签: javascript react-native async-await fetch asyncstorage

我尝试使用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})
}

1 个答案:

答案 0 :(得分:2)

试试这个:

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