React Native提供的AsyncStorage来实现类似localStorage的功能
import React from 'react';
import { Text, View, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
export default class StorageExample 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>
<Button onPress={this._storeData} title="Store Data" />
<Button onPress={this._retrieveData} title="Retrieve Data" />
<Text>{this.state.data}</Text>
</View>
);
}
}
这段代码展示了如何在React Native应用中使用AsyncStorage来存储和检索数据。_storeData
函数用于存储数据,_retrieveData
函数用于检索数据,并且这些操作都是异步的,以防止阻塞UI线程。
评论已关闭