官方推薦使用框架:async-storage
存儲(chǔ)設(shè)計(jì)到了IO操作,IO操作的時(shí)間是不可預(yù)知的,所以該框架是異步存儲(chǔ)框架。
首選下載該框架:
$ yarn add @react-native-community/async-storage
然后進(jìn)行關(guān)聯(lián):
$ react-native link @react-native-community/async-storage
接下來(lái)就可以使用了。使用的時(shí)候需要先導(dǎo)入js:
import AsyncStorage from '@react-native-community/async-storage';
存儲(chǔ)數(shù)據(jù):
storeData = async () => {
try {
await AsyncStorage.setItem('@storage_Key', 'stored value')
} catch (e) {
// saving error
}
}
讀取數(shù)據(jù):
getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}