探索React Native社区的Async Storage:一款高效、可靠的本地存储解决方案
import React from 'react';
import { View, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
export default class AsyncStorageExample extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ''
};
}
_storeData = async () => {
try {
await AsyncStorage.setItem('@storage_Key', 'Stored Value');
this.setState({data: 'Data has been stored!'});
} catch (error) {
this.setState({data: 'Error storing data.'});
}
}
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key');
if(value !== null) {
this.setState({data: value});
}
} catch (error) {
this.setState({data: 'Error retrieving data.'});
}
}
render() {
return (
<View>
<Text>{this.state.data}</Text>
<Button title="Store Data" onPress={this._storeData} />
<Button title="Retrieve Data" onPress={this._retrieveData} />
</View>
);
}
}
这段代码展示了如何在React Native应用中使用Async Storage来存储和检索数据。_storeData
函数用于存储数据,_retrieveData
函数用于检索数据。两个函数都是异步的,并使用try...catch
来处理可能出现的错误。这是一个简单而实用的例子,展示了Async Storage的基本用法。
评论已关闭