React Native AsyncStorage getItem returns 承诺不值

React Native AsyncStorage getItem returns promise not value

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

如果我通过 :

控制台记录这个

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

它returns 像这样的 promise 对象

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

: 对象

如何从 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();

顺便说一下,他们在文档中使用了 await。我尝试使用它,但页面没有 loading.Here 并附有屏幕截图。

使用Async/Await:

async _getStorageValue(){
  var value = await AsyncStorage.getItem('ITEM_NAME')
  return value
}

您必须调用为

getUserToken().then(res => {
    console.log(res);
  });

因为这是一个异步调用。

这就是我通常设法从本地存储中获取值的方式:

const getItemFromStorage = async () => {
  try {
       await AsyncStorage.getItem('ITEM_NAME', (error: any, result: any) => {
         if (result) {
           console.log(result);
         }else{
           console.log(JSON.stringfy(error));
         }
       });
     } catch (error) {
       console.log(error);
     }
}