@yzzer
2020-05-20T10:24:21.000000Z
字数 2758
阅读 952
React Native 提供了 AsyncStorage 组件用于存储数据。
在 0.60 版本之前,这个组件是内置的,0.60 版本把它移到了 react-native-community/react-native-async-storage。
AsyncStorage 是一个简单的,未加密的,异步的,持久的键值存储系统。
AsyncStorage 是一个全局的存储系统,没有实例这一概念。要存储数据就往里面扔,要读取数据就发起请求。
AsyncStorage 对外提供了简单的 JavaScript 接口。每一个接口都是 异步 的,每一个接口都返回一个 Promise 对象。
虽然之前的版本都是内置,但 0.60 版本将组件移到了 react-native-community/react-native-async-storage。
为了兼容所有版本,我们推荐安装 react-native-community/react-native-async-storage。
yarn add @react-native-community/async-storage
或
npm i @react-native-community/async-storage
React Native 0.60+ 版本会自动链接。
但之前的版本则需要我们手动链接
react-native link @react-native-community/async-storage
如果你从低版本升级到 0.60+ 版本,反而要删除链接,命令如下
react-native unlink @react-native-community/async-storage
import AsyncStorage from '@react-native-community/async-storage';
| 方法 | 说明 |
|---|---|
| getItem() | 根据给定的 key 来读取数据 |
| setItem() | 将一个键值对添加到系统中,如果已经存在 key 则覆盖 |
| removeItem() | 根据给定的 key 删除指定的键值对 |
| getAllKeys() | 返回数据库中所有的 键 |
| multiGet() | 根据给定的 key 列表获取多个键值对 |
| multiSet() | 将多个键值对存储到系统中 |
| multiRemove() | 根据多个 key 删除多个键值对 |
| clear() | 清空整个数据库系统 |
每一个接口的详细信息,可以 官方 API 文档
存储数据
storeData = async () => {try {await AsyncStorage.setItem('@storage_Key', 'stored value')} catch (e) {// 保存失败}}
读取数据
getData = async () => {try {const value = await AsyncStorage.getItem('@storage_Key')if(value !== null) {// 之前存储的数据}} catch(e) {// 读取数据失败}}
constructor() 构造函数中先初始化一个默认值componentDidMount() 中。下面的代码演示了如何在存储数据组件 AsyncStorage 中存储和读取数据。
import React, { Component } from 'react'import { Text, View, Alert,TextInput, StyleSheet,TouchableHighlight } from 'react-native'import AsyncStorage from '@react-native-community/async-storage';export default class App extends Component {state = {'name': '你好BUCT','inputText':'你好,yzzer',}async readName() {try {const value = await AsyncStorage.getItem('name')if(value !== null) {this.setState({ 'name': value })}Alert.alert("读取数据成功")} catch(e) {console.log(e);Alert.alert("读取数据失败!")}}setName = () => {AsyncStorage.setItem('name', this.state.inputText);Alert.alert("保存成功!")}render() {return (<View style = {styles.container}><TextInputstyle = {styles.textInput}autoCapitalize = 'none'value={this.state.inputText} /><View style={{flexDirection:'row'}}><TouchableHighlight style={[styles.button,{marginRight:8}]} onPress={this.setName}><Text style={styles.buttonTxt}>保存</Text></TouchableHighlight><TouchableHighlight style={[styles.button,{backgroundColor:'blue'}]} onPress={this.readName.bind(this)}><Text style={styles.buttonTxt}>读取</Text></TouchableHighlight></View><View style={{marginTop:8}}><Text>当前的值:{this.state.name}</Text></View></View>)}}const styles = StyleSheet.create ({container: {margin:10},textInput: {margin: 5,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'}})
演示