1、下载
yarn add @react-native-community/async-storage
2、引入
import AsyncStorage from '@react-native-community/async-storage';
3、存储组件的所有操作都是异步的,返回promise对象
最后好异步函数内部包裹try-catch
async xx(){
try{
//设置
await AsyncStorage.setItem('键名','值',回调函数(可选))
//读取
await AsyncStorage.getItem('键名',回调函数(可选))
//删除
await AsyncStorage.removeItem('键名',回调函数(可选))
}catch(e){...}
}
代码示例:
import React,{Component} from 'react'
import {View,StyleSheet,Text,TextInput,TouchableHighlight, Alert, TouchableOpacity} from 'react-native'
import AsyncStorage from '@react-native-community/async-storage';
export default class App extends Component{
state={
name:'jeff',
inputText:'好帅'
}
//AsyncStorage都是异步操作,返回promise对象
async readName()
{
try{
//读
const value=await AsyncStorage.getItem('name')
if(value){
this.setState({name:value});
Alert.alert('成功');
}
}catch(e){
Alert.alert('读取失败');
}
}
async setName(){
try{
await AsyncStorage.setItem('name',this.state.name+'s');
Alert.alert('设置成功');
await AsyncStorage.removeItem('name',function(){
Alert.alert('删除成功');
})
}catch(e){
Alert.alert('设置失败');
}
}
render()
{
return(
<>
<View>
<TextInput
style={style.textInput}
autoCapitalize='none'
value={this.state.inputText}
/>
<View style={{flexDirection:'row'}}>
<TouchableOpacity style={[style.button,{marginRight:8}]} onPress={this.setName.bind(this)} >
<Text style={style.buttonTxt}>保存</Text>
</TouchableOpacity>
<TouchableHighlight style={[style.button,{backgroundColor:'blue'}]} onPress={this.readName.bind(this)}>
<Text style={style.buttonTxt}>读取</Text>
</TouchableHighlight>
</View>
<View style={{margin:8}}>
<Text>{this.state.name}</Text>
</View>
</View>
</>
)
}
}
const style=StyleSheet.create({
textInput:{
margin:4,
height:44,
width:'100%',
borderWidth:1,
borderColor:'#dddddd'
},
button:{
flex:1,
height:44,
justifyContent:"center",
alignItems:'center',
width:100,
backgroundColor:'red'
},
buttonTxt:{
justifyContent:'center',
color:'#ffffff'
}
})