AsyncStorage 是一个简单的、异步的、持久化的Key-Value存储系统,它对于App来说是全局性的。它用来代替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() {// 同步获取数据
const value = await AsyncStorage.getItem('product')
alert(value)
}
}
- 异步 使用回调
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() { //回调获取数据(异步)
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
}
//仅仅需要定义要增加或更新的项
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
}
//仅仅需要定义要增加或更新的项
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')
}
})
}
}
- 此外, 还有设置多个值, 获取多个值, 删除多个值