使用AsyncStorage存儲數據
在之前的示例中,當我們每次重新運行程序時,原先的todo list就丟失了。在今天的課程里,我們將使用AsyncStorage來存儲數據,這樣只要不卸載程序,即便重新運行程序,數據也不會丟失。
導入AsyncStorage
在app.js里,我們導入AsyncStorage
import {View, Text, StyleSheet, Platform, ListView, Keyboard, AsyncStorage} from "react-native";
使用AsyncStorage
我們將在App類的componentWillMount方法里使用AsyncStorage將數據取出來,componentWillMount在組件的生命周期中,當組件即將Mount的時候會自動調用。下面一個圖可以簡單了解一下React Native的組件生命周期。

也就是在render()調用之前,react native會調用其componentWillMount方法。
componentWillMount() {
AsyncStorage.getItem("items").then(json => {
try {
const items = JSON.parse(json);
this.setSource(items, items);
} catch (e) {
}
});
}
更新AsyncStorage
當我們增加、修改、刪除了todo之后,我們需要將數據更新回AsyncStorage,我們只需要在我們的setSource里做這個步驟就可以了。
/*
一個通用的setSource方法,方便調用
*/
setSource(items, itemsDatasource, otherState = {}) {
this.setState({
items,
dataSource: this.state.dataSource.cloneWithRows(itemsDatasource),
...otherState
});
AsyncStorage.setItem("items", JSON.stringify(items));
}
我們在今天的代碼里使用了JSON.parse()方法和JSON.stringify()方法,parse方法是將一個json格式的字符串轉成一個對象,stringify則相反,將一個對象轉成json格式的字符串。