首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React原生AsyncStorage承诺

React原生AsyncStorage承诺
EN

Stack Overflow用户
提问于 2019-07-15 04:31:44
回答 1查看 275关注 0票数 1

因此,我现在使用react原生中的AsyncStorage来存储使用axios发出请求的api。当我调用AsyncStorage来获取一个item时,我得到的是Object对象而不是键。

我尝试了异步等待函数来解析promise以获得值,但我仍然得到promise而不是promise中的值。我还尝试用then返回值,然后返回值。

代码语言:javascript
复制
import {AsyncStorage} from 'react-native';

class APIToken {
    constructor(){}
    async get(){
        try {
            const token = await AsyncStorage.getItem('api_token');
            if (token !== null) {
              // We have data!!
              console.log(token);
              return token
            }
          } catch (error) {
            // Error retrieving data
          }
          //return null
    }
    async set(token){
        try {
            await AsyncStorage.setItem('api_token', token);
            return token
          } catch (error) {
            // Error saving data
          }
          //return null
    }
}

export default APIToken

const key = async function() {
    const k = await (new APIToken()).get()
    return k
  }


const api = axios.create({
    baseURL: Config.API_URL_V1,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + key(),
        'Cache-Control': 'no-cache'
    }
  });
EN

回答 1

Stack Overflow用户

发布于 2019-07-15 05:37:42

AsyncStorage将数据保存为字符串。您是否尝试过在保存之前对键调用JSON.stringify,并在从存储中检索值之后调用JSON.parse?

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57030954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档