1:常用方法
getItem(key:string,callback?:?(error:?Error,result:?string)=>void) 静态方法,该通过key字段来进行查询存储的数据,把该结果值作为参数传入第二个callback方法。如果发生错误,会把Error对象传入callback方法。该方法最终返回一个Promise对象
setItem(key:string,value:string,callback?:?(error:?Error)=>void) 静态方法,该根据key字段设置value内容,完成之后进行回调callback方法。如果发生错误会把Error对象传入callback方法中。该方法返回一个Promise对象。
removeItem(key:string,callback?:?(error:?Error)=>void) 静态方法,根据key进行删除值,成功之后进行回调callback方法。如果发生错误会把Error对象传入callback方法中。该方法返回一个Promise对象。
2:带有的方法
- static getItem(key:string , callback:(error,result)): 根据键来获取值,获取的结果会在回调函数中。
- static setItem(key:string , value:string , callback:(error)): 设置键值对。
- static removeItem(key:string , callback:(error)): 将根据键移出一项
- static mergeItem:(key:string , value:string , callback:(error)): 合并现有的值和输入值。
- static clear(callback:(error)): 清除所有的项目。
- static getAllKeys(callback:(error)): 获取所有的键。
- static multiGet(keys,callback:(errors,result)):获取多项,其中keys是字符串数组。
- static multiSet(keyValuePairs,callback:(errors)):设置多项,其中keyValuePairs是字符串的二维数组。
- static multiRemove(keys,callback(errors)):删除多项,其中keys是字符串数组。
- static multiMerge(keyValuePairs,callback:(errors)):多个键值合并,其中keyValuePairs是字符串中的二维数组。
2:安装react-native-easy-toast(简单提示框)
3:代码
import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput, AsyncStorage, } from 'react-native'; import Toast,{DURATION} from 'react-native-easy-toast';//导入弹出框组件 const KEY='text';//指定key type Props = {}; export default class AsyncStorageTest extends Component { constructor(props) { super(props); } //保存 save() { AsyncStorage.setItem(KEY, this.text, (error)=> { //设置键值对 key:value if (!error) { this.toast.show('保存成功', DURATION.LENGTH_LONG);//设置提示框,并设置持续时间 } else { this.toast.show('保存失败', DURATION.LENGTH_LONG); } }); } //取出 get() { AsyncStorage.getItem(KEY, (error, result)=> { if (error) { this.toast.show('取出失败', DURATION.LENGTH_LONG); } else { if (result) { this.toast.show('取出的结果为:' + result, DURATION.LENGTH_LONG); } else { this.toast.show('没有找到对应的内容', DURATION.LENGTH_LONG); } } }); } //移除 remove(){ AsyncStorage.removeItem(KEY,(error)=>{ if (!error) { this.toast.show('移除成功', DURATION.LENGTH_LONG); } else { this.toast.show('移除失败', DURATION.LENGTH_LONG); } }); } render() { return ( <View> <TextInput style={{height:80}} onChangeText={(text)=> { this.text = text; }} /> <View style={{flexDirection: 'row'}}> <Text style={styles.text} onPress={()=>this.save()}> 保存 </Text> <Text style={styles.text} onPress={()=>this.remove()}> 移除 </Text> <Text style={styles.text} onPress={()=>this.get()}> 取出 </Text> </View> <Toast ref={toast=> {//提示框展示位置 this.toast = toast }}/> </View> ) } } const styles = StyleSheet.create({ text: { fontSize: 20, margin:10 } });