使用AsyncStorage存儲(chǔ)數(shù)據(jù)
在之前的示例中,當(dāng)我們每次重新運(yùn)行程序時(shí),原先的todo list就丟失了。在今天的課程里,我們將使用AsyncStorage來(lái)存儲(chǔ)數(shù)據(jù),這樣只要不卸載程序,即便重新運(yùn)行程序,數(shù)據(jù)也不會(huì)丟失。
導(dǎo)入AsyncStorage
在app.js里,我們導(dǎo)入AsyncStorage
import {View, Text, StyleSheet, Platform, ListView, Keyboard, AsyncStorage} from "react-native";
使用AsyncStorage
我們將在App類(lèi)的componentWillMount
方法里使用AsyncStorage
將數(shù)據(jù)取出來(lái),componentWillMount
在組件的生命周期中,當(dāng)組件即將Mount
的時(shí)候會(huì)自動(dòng)調(diào)用。下面一個(gè)圖可以簡(jiǎn)單了解一下React Native的組件生命周期。
也就是在render()
調(diào)用之前,react native會(huì)調(diào)用其componentWillMount
方法。
componentWillMount() {
AsyncStorage.getItem("items").then(json => {
try {
const items = JSON.parse(json);
this.setSource(items, items);
} catch (e) {
}
});
}
更新AsyncStorage
當(dāng)我們?cè)黾印⑿薷摹h除了todo之后,我們需要將數(shù)據(jù)更新回AsyncStorage,我們只需要在我們的setSource
里做這個(gè)步驟就可以了。
/*
一個(gè)通用的setSource方法,方便調(diào)用
*/
setSource(items, itemsDatasource, otherState = {}) {
this.setState({
items,
dataSource: this.state.dataSource.cloneWithRows(itemsDatasource),
...otherState
});
AsyncStorage.setItem("items", JSON.stringify(items));
}
我們?cè)诮裉斓拇a里使用了JSON.parse()
方法和JSON.stringify()
方法,parse方法是將一個(gè)json格式的字符串轉(zhuǎn)成一個(gè)對(duì)象,stringify則相反,將一個(gè)對(duì)象轉(zhuǎn)成json格式的字符串。