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/あなたがデータを更新する必要がある場合には、まず変数にデータをバインドし、その変数への変更を行い、データを取得し、 、上記のコードをコピーして、私の実際のプロジェクトのコードから短縮した
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);
}
}
:次はAsyncStorage
に新しいデータを書き込みます何か問題があれば教えてください!
あなたはまだそれを動作させましたか?はいの場合は、投票も考慮してください。ありがとう^^! – thinhvo0108