根据我之前成功的 react-native 项目的经验,你可以使用AsyncStorage
,简单但足够强大,你可以存储任何你想要的东西!
此外,您还应该使用flux
or redux
,它将为您提供一个存储解决方案,您可以在其中轻松读取和存储相关数据AsyncStorage
(无处不在,在每一页上)!
这些步骤是(主要流程关于如何组织数据和构建逻辑的想法):
0/导入库:
import React, { Component } from 'react';
import {
AsyncStorage,
// ...
} from 'react-native';
1/从您的 API或某处(本地文件等)获取数据,然后将数据写入(保存)到 AsyncStorage:
async firstWriteFavorite() {
fetch("YOUR_API_URL", {method: "GET", headers: {'Cache-Control': 'no-cache'}})
.then((response) => response.json())
.then((responseJson) => {
try {
// make sure you write a STRING into AsyncStorage,
// and also be careful which key of the JSON should be written, the below line is just a good example:
await AsyncStorage.setItem("@PROJECT_NAME:your_favorite_array", JSON.stringify(responseJson.response));
// if you use flux or redux here, you can perform some action here, then you can load the data everywhere later:
// FavoriteActionCreators.set_favorite(responseJson.response);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
})
.catch((error) => {
console.log("Error in first getting ajax data!", error);
}
);
}
2/从以下位置检索数据AsyncStorage
:
async loadFavorite() {
try {
var fav_array_string = await AsyncStorage.getItem("@PROJECT_NAME:your_favorite_array");
// the above returned value is a STRING, then you can split it, or do whatever based on the structure you have written
var real_fav_id_array = fav_array_string.split('YOUR_SEPARATOR');
// ...
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
3/当您需要更新数据时,首先检索数据,然后将数据绑定到一个变量并对该变量进行更改,然后将新数据写入AsyncStorage
:
async saveFavorite() {
// loadFavorite() here,
// make sure you've got data "your_new_JSON_data" which has been converted into object, then maybe: "your_new_JSON_data.push({NEW_OBJ})";
// after that, SAVE NEW DATA now:
try {
await AsyncStorage.setItem("@PROJECT_NAME:your_favorite_array", JSON.stringify(your_new_JSON_data));
// same here, if you use flux or redux here, you can save the new data here:
// FavoriteActionCreators.set_favorite(your_new_JSON_data);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
以上代码是从我的真实项目代码中复制和缩短的,如果您有任何问题,请尝试告诉我!