React Native - 将新项目推送到现有的 AsyncStorage 密钥?

React Native - Push new item(s) to existing AsyncStorage key?

我有几个场景需要在 AsyncStorage 中存储项目并将新数据推送到它们各自的键。其中之一是存储在 AsyncStorage 中的 10 个国家/地区的列表,如下所示:

AsyncStorage.setItem('countries', JSON.stringify(countries));

我尝试了以下方法,其中 country 是我想要 push/add 到预先存在的 countries 的新项目:

AsyncStorage.push('countries', JSON.stringify(country));

那当然不行...

如前所述,我也有一些需要此功能的场景。我正在尝试找到一个解决方案,它具有可重用的 React Native AsyncStorage 函数来处理传递的 keydata,并负责设置项目,或者推送到项目(如果有)存在。

知道如何使用 AsyncStorage 有效地完成此功能吗?

var countries = await AsyncStorage.getItem('countries');
AsyncStorage.setItem('countries', countries += JSON.stringify(country));

如果你试图在连接两个字符串后获取 'countries' 数据,你显然会无效 json 像这样:{one json obj}{other json obj}.

您必须解析 JSON 然后像这样推送它:

var countries = await AsyncStorage.getItem('countries');
countries = JSON.parse(countries);
countries.push(country);

一旦我们推送了最新的国家/地区,我们就可以将更新后的国家/地区对象保存到 localstorage.

AsyncStorage.setItem('countries', JSON.stringify(countries));

显然你会在抓取和检索本地存储数据时添加 try + catch 块(我刚刚将它们排除在外在这里)。

以下代码段将添加一个具有现有记录的新项目,

var countries = AsyncStorage.getItem('countries');
AsyncStorage.setItem('countries', countries.concat(country));