本文介绍了应用程序重启时 AsyncStorage 数据发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在调用一个 JSON api 来设置一个身份验证令牌,我将它存储在 AsyncStorage 中以在应用程序生命周期之间保持不变,因此用户不必每次都登录.

I'm currently calling a JSON api to set an auth token which I'll just be storing in the AsyncStorage to persist between app life so a user doesn't have to log in every single time.

我目前正在像这样设置令牌:

I'm currently setting that token like so:

fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(this.state)
  })
    .then( resp => {
      return resp.json();
    })
    .then( async (data) => {
      if ('error' in data) {
        this.setState({
          error: data.error,
          password: ''
        })
        this.secondTextInput.focus();
      }

      if ('access_token' in data) {
        try {
          await AsyncStorage.setItem('access_token', data.access_token);
        } catch (error) {
          return error;
        }

        this.props.navigation.navigate('Main');

      }
    })
    .catch(
      error => {
        console.error(error)
        return error;
      }
    );

如果我然后调用 AsyncStorage.getItem('access_token') 杀死应用程序或重新加载它之后,我将得到以下输出:

If I then call AsyncStorage.getItem('access_token') After killing the app or reloading it I'm winding up with this output:

{
    "_40":0,
    "_65":0,
    "_55":null,
    "_72":null
}

如果我随后调用 AsyncStorage.getItem('access_token') 之前 终止应用程序或重新加载它,我将获得正确的访问令牌.我已经仔细检查了代码,我没有在其他任何地方使用 AsyncStorage.setItem('access_token').

If I then call AsyncStorage.getItem('access_token') Before killing the app or reloading it I'm winding up with the correct access token. I've double checked the code and I'm not using AsyncStorage.setItem('access_token') anywhere else.

这是我检索令牌的方式:

This is how I'm retrieving my token:

  componentDidMount() {

  console.warn('Mounting');

  try {

      let token = AsyncStorage.getItem('access_token');
      console.warn(token);

      if(token !== null) {
          console.error(token);
      }

  }   catch (error) {}

推荐答案

AsyncStorage.getItem() 和 setItem() 一样是一个异步操作,所以你需要等到 Promise 解决了再记录.

AsyncStorage.getItem() is a asynchronous action just like setItem(), so you need to wait until the Promise has been resolved before logging.

编辑提示:如果你看到一些奇怪的输出,它总是与尚未解决或拒绝的 Promise 相关

EditTip: if you see some strange output like that it is always related to a Promise which is not yet resolved or rejected

这篇关于应用程序重启时 AsyncStorage 数据发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:56