react native 本地存储 AsyncStorage
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
export default function App() {
const [data, setData] = useState('');
const saveData = async (newData) => {
try {
await AsyncStorage.setItem('data', newData);
setData(newData);
} catch (e) {
console.log('保存数据失败:', e);
}
};
const loadData = async () => {
try {
const value = await AsyncStorage.getItem('data');
if (value !== null) {
setData(value);
}
} catch (e) {
console.log('加载数据失败:', e);
}
};
const clearData = async () => {
try {
await AsyncStorage.clear();
setData('');
} catch (e) {
console.log('清除数据失败:', e);
}
};
return (
<View>
<Text>{data}</Text>
<Button title="保存数据" onPress={() => saveData('Hello, AsyncStorage!')} />
<Button title="加载数据" onPress={loadData} />
<Button title="清除数据" onPress={clearData} />
</View>
);
}
这段代码展示了如何在React Native应用中使用AsyncStorage进行本地数据的保存、加载和清除。使用了函数组件和Hooks API (useState
),并包含了异常处理。
评论已关闭