react native学习笔记16——存储篇(1)AsyncStorage
前言React Native中常用的数据本地化存储的方法有如下几种:
本文主要主要介绍第一种——AsyncStorage。 AsyncStorage介绍AsyncStorage是react native提供的轻量存储器,类似Android中的SharePreference, iOS中的NSUserDefault,以键值对的形式存储将信息存储在本地,它是一个简单的、未加密的、异步的、持久化的Key-Value 存储系统,对于App来说是全局性的。官方建议使用时在AsyncStorage的基础上做一层抽象封装,而不是直接使用AsyncStorage。 下面是使用AsyncStorage存储数据、获取数据的简单示例。 try {
await AsyncStorage.setItem('samplekey','lalala.');
} catch (error) {
// Error saving data
}
获取数据: try {
const value = await AsyncStorage.getItem('samplekey');
if (value !== null){
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
常用的方法
使用实例下面示例中主要通过 import React,{ Component } from 'react';
import {
StyleSheet,View,Text,Dimensions,Button,AsyncStorage
} from 'react-native';
const {width,height} = Dimensions.get('window');
var data = "";
const AsyncStorageKey = "ASE_";
export default class AsyncStorageExample extends Component {
constructor(props) {
super(props);
this.state = {
data:""
};
}
setData(text){
AsyncStorage.setItem(AsyncStorageKey,text,()=>{
this.setState({
data:text,});
});
}
delData(){
AsyncStorage.getItem(AsyncStorageKey,(error,text)=>{
if(text=== null ){
alert(AsyncStorageKey +"没有对应的值");
}else{
//移除键-值对
AsyncStorage.removeItem(AsyncStorageKey,()=>{
this.setState({
data:"",},()=>{
alert('删除成功');
});
});
}
});
}
render() {
return (
<View style={styles.container}> <Button onPress={this.setData.bind(this,"我用 AsyncStorage存了一条信息")} style={styles.itemView} title="存储数据"> </Button> <Button onPress={this.delData.bind(this)} style={styles.itemView} title="删除数据" > </Button> <Text style={{paddingTop:40}}> AsyncStorage存储的值是: </Text> <Text> {this.state.data} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1,backgroundColor: '#f2f2f2',paddingTop:20,itemView:{ backgroundColor:'grey',height:44,width:width,justifyContent:'center',marginTop:10,itemText:{ fontSize:15,color:'#ffffff',textAlign:'left',marginLeft:20,});
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |