【问题标题】:How to store a Map using AsyncStorage in React-Native?如何在 React-Native 中使用 AsyncStorage 存储地图?
【发布时间】:2020-08-25 23:40:51
【问题描述】:
import * as React from 'react';

let paths = new Map();
  
export function AddPath(path) {
    if (paths.has(path)){
        return
    }
    else{
        paths.set(path, false);
    }

}

export function CompletedPath(path) {
    paths.set(path, true);
}

以上是我的代码正常的样子。它按预期运行。我正在创建一个名为路径的地图以存储一些重要数据。它的值为真或假,而它的键是 JSON 对象。 我需要做的是将此 Map 保存到异步存储中,以便在关闭应用程序后重新打开应用程序时可以检索到它。 这是我目前修改代码的尝试:

import * as React from 'react';
import AsyncStorage from '@react-native-community/async-storage';

let paths = new Map();

const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('Map')
      let paths = JSON.parse(jsonValue);
    } catch(e) {
      // error reading value  
    }
    alert(paths)
}

const storeData = async (data) => {
    try {
      const jsonValue = JSON.stringify(data)
      await AsyncStorage.setItem('Map', jsonValue)
    } catch (e) {
      // saving error
    }
}

getData();
  
export function AddPath(path) {
    if (paths.has(path)){
        return
    }
    else{
        paths.set(path, false);
        storeData(paths);
    }

}

export function CompletedPath(path) {
    paths.set(path, true);
    storeData(paths);
}

我像往常一样创建路径 Map,然后调用 getData() 来查看该映射是否已存在于异步存储中。然后,在我之前更新地图的地方,我也会更新异步存储。

但是,我无法让它工作。当我重新打开应用程序时,“路径”地图始终显示为空。

这可能是我如何存储异步存储路径的问题,因为它是一个 Map 而不是 JSON 对象?

有什么想法吗?

【问题讨论】:

    标签: javascript android react-native mobile asyncstorage


    【解决方案1】:

    如果您对Map 执行JSON.stringify,它将被转换为{}。

    MAP 转换为Array 并使用stringify

    const map = new Map();
    map.set('test',true);
    console.log(JSON.stringify(map));
    console.log(JSON.stringify(Array.from(map.entries())));

    字符串化

    const jsonValue = JSON.stringify(Array.from(data.entries()));
    

    解析

    let paths = new Map(JSON.parse(jsonValue));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2018-10-16
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多