【问题标题】:AsyncStorage.getItem returning undefined when using fetch - React-Native使用 fetch 时 AsyncStorage.getItem 返回 undefined - React-Native
【发布时间】:2018-02-28 09:42:37
【问题描述】:

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

【问题讨论】:

  • 为什么要同时使用 fetch 和 await? await 解决承诺并返回结果。你应该做类似 const response = await fetch(...);常量结果 = 等待 response.json();等待 AsyncStorage.setItem(..., result.id_token)
  • 按照你的做法,你实际上并没有等待所有承诺的结果。

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


【解决方案1】:

试试这个:

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

【讨论】:

  • hmm....遇到同样的错误cannot read property getItem of defined
  • 如果错误是“无法读取未定义的属性 getItem”,那么您没有正确导入 AsyncStorage。
  • 它是 react-native,不是 react
  • 你是正确的。将 AsyncStorage 更改为从 React-Native 导入而不是 react 解决了这个问题。谢谢!
  • 不推荐使用此方法以及从 react-native 导入。 import AsyncStorage from "@react-native-community/async-storage";
猜你喜欢
  • 1970-01-01
  • 2018-04-17
  • 2019-08-04
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
相关资源
最近更新 更多