学习交流:https://gitee.com/potato512/Learn_ReactNative
react-native学习交流QQ群:806870562
react-native中主要使用AsyncStorage进行数据缓存操作,其实现原理是key-value的形式。
主要功能有:保存(修改)、删除(删除指定值,删除所有值)、读取。
效果图
代码示例
import React from 'react'; import {View,Text,TouchableOpacity,Alert,AsyncStorage,StyleSheet} from 'react-native'; let message1 = "devZhang is an iOS developer."; let message2 = "devZhang comes from GuangDong."; export default class DataStoragePage extends React.Component { render() { return( <View style={styles.container}> <Text style={styles.text}>数据缓存功能</Text> <TouchableOpacity style={styles.text} onPress={saveData}> <Text>保存数据</Text> </TouchableOpacity> <TouchableOpacity style={styles.text} onPress={readData}> <Text>读取数据</Text> </TouchableOpacity> <TouchableOpacity style={styles.text} onPress={deleteData}> <Text>删除数据</Text> </TouchableOpacity> <TouchableOpacity style={styles.text} onPress={modifyData}> <Text>修改数据</Text> </TouchableOpacity> <TouchableOpacity style={styles.text} onPress={deleteAllData}> <Text>删除所有数据</Text> </TouchableOpacity> </View> ) } } const saveData = () => { AsyncStorage.setItem('keyMessage',JSON.stringify(message1),(error) => { let value = "保存数据成功:" if (error) { value = "保存数据失败:" } Alert.alert(value + message1) }); }; const readData = async () => { // 方法1 // try { // let result = await AsyncStorage.getItem("keyMessage") // Alert.alert("读取成功:" + result) // } catch(error) { // Alert.alert("读取失败:" + error) // } // 方法2 AsyncStorage.getItem('keyMessage').then(result => { Alert.alert("读取成功:" + result) }).catch(error => { Alert.alert("读取失败:" + error) }) // 方法3 // AsyncStorage.getItem('keyMessage',(error,result) => { // let value = "读取数据成功:" // let obj = JSON.parse(result); // if (error) { // value = "读取数据失败:" // } // Alert.alert(value + obj) // }); }; const deleteData = () => { AsyncStorage.removeItem('keyMessage',(error) => { let value = "删除数据成功:" if (error) { value = "删除数据失败:" } Alert.alert(value + error) }); }; const modifyData = () => { AsyncStorage.setItem('keyMessage',JSON.stringify(message2),(error) => { let value = "修改数据成功:" if (error) { value = "修改数据失败:" } Alert.alert(value + message2) }); }; const deleteAllData = () => { AsyncStorage.clear((error) => { let value = "删除所有数据成功:" if (error) { value = "删除所有数据失败:" } Alert.alert(value + error) }); }; const styles = StyleSheet.create({ container: { display:"flex",flexDirection:"column",backgroundColor: 'white',alignItems: 'center',},text: { marginTop:10,justifyContent:"center",alignItems:'center',backgroundColor:'red',fontSize:20,color:"black",height:40,});