AsyncStorage 是一個(gè)簡(jiǎn)單的丰刊、異步的惶凝、持久化的Key-Value存儲(chǔ)系統(tǒng),它對(duì)于App來(lái)說(shuō)是全局性的元暴。它用來(lái)代替LocalStorage。
- 同步 async await
export default class AwesomeProject extends Component {
render() {
return (
<View>
<Text onPress={this.onPress}>
save date
</Text>
<Text onPress={this.onPressLoad}>
get data
</Text>
</View>
);
}
onPress() {
AsyncStorage.setItem('product', 'apple')
}
async onPressLoad() {// 同步獲取數(shù)據(jù)
const value = await AsyncStorage.getItem('product')
alert(value)
}
}
- 異步 使用回調(diào)
export default class AwesomeProject extends Component {
render() {
return (
<View>
<Text onPress={this.onPress}>
save date
</Text>
<Text onPress={this.onPressLoad}>
get data
</Text>
</View>
);
}
onPress() {
AsyncStorage.setItem('product', 'apple')
}
onPressLoad() { //回調(diào)獲取數(shù)據(jù)(異步)
AsyncStorage.getItem('product', (err, res) => {
if(err) {
alert('no keywords')
} else {
alert('first:' + res)
}
})
}
}
- mergeItem 合并
export default class AwesomeProject extends Component {
render() {
return (
<View>
<Text onPress={this.onPress}>
save date
</Text>
<Text onPress={this.onPressLoad}>
get data
</Text>
</View>
);
}
async onPress() {
let obj1 = {
name: 'Async',
age: 14
}
//僅僅需要定義要增加或更新的項(xiàng)
let obj2 = {
name: 'Callback',
age: 1100
}
await AsyncStorage.setItem('hero', JSON.stringify(obj1))
await AsyncStorage.mergeItem('hero', JSON.stringify(obj2))
}
onPressLoad() {
alert(AsyncStorage.getItem('hero')))
}
}
- removeItem
export default class AwesomeProject extends Component {
render() {
return (
<View>
<Text onPress={this.onPress}>
save date
</Text>
<Text onPress={this.onPressLoad}>
get data
</Text>
<Text onPress={this.removeData}>
remove data
</Text>
</View>
);
}
async onPress() {
let obj1 = {
name: 'Async',
age: 14
}
//僅僅需要定義要增加或更新的項(xiàng)
let obj2 = {
name: 'Callback',
age: 1100
}
await AsyncStorage.setItem('hero', JSON.stringify(obj1))
await AsyncStorage.mergeItem('hero', JSON.stringify(obj2))
}
async onPressLoad() {
const msg = await AsyncStorage.getAllKeys((err, keys) => {
return keys
})
alert(msg)
}
removeData() {
AsyncStorage.removeItem('hero', (err) => {
if(err) {
alert('error')
} else {
alert('success')
}
})
}
}
- 此外, 還有設(shè)置多個(gè)值, 獲取多個(gè)值, 刪除多個(gè)值