React Native AsyncStorage getItem 返回承诺而不是值

2024-01-22

我有一个登录表单,我可以发布表单值。成功的 POST 请求后,我会收到从 API 返回的身份验证令牌。我需要将此令牌保存在本地存储中以供将来参考。为了保存此身份验证令牌,我使用 AsyncStorage。我用了AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token);setItem方法来保存数据。

如果我通过以下方式控制台记录此内容:

console.log(AsyncStorage.setItem(STORAGE_KEY));

它作为承诺对象返回,如下所示

    Promise {_45: 0, _81: 0, _65: null, _54: null}
_45
:
0
_54
:
null
_65
:
"efcc06f00eeec0b529b8"
_81
:
1
__proto__

: Object

如何从 AsyncStorage.getItem 方法获取确切的值?

这是我的获取方法

fetch('http://54.255.201.241/drivers', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      first_name: this.state.firstName,
      mobile_number: this.state.mobileNumber,
      vehicle_number: this.state.vehicleNumber,
      vehicle_type_id: 1,
    })
  }).then((response) => response.json()).then((responseData) => {
    if (JSON.stringify(responseData.mobile_number) == (this.state.mobileNumber))
    {
      AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token);
      console.log(AsyncStorage.getItem(STORAGE_KEY));
      this.props.navigator.push({id: 'Otp'})
    }
    else
    {
      Alert.alert("SignUp Failed","Mobile number already taken.")  
    }
  })
  .done();

BTW in documentation they have used await. I tried using that but the pages are not loading.Here with attached the screenshot.enter image description here


使用异步/等待:

async _getStorageValue(){
  var value = await AsyncStorage.getItem('ITEM_NAME')
  return value
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native AsyncStorage getItem 返回承诺而不是值 的相关文章

随机推荐