【发布时间】:2023-10-24 22:11:01
【问题描述】:
众所周知,我们不能在 React Native 中使用 LocalStorage。我尝试创建一个 useAsyncStorage 自定义钩子,它与 LocalStorage 自定义钩子具有相同的功能,以响应将数据存储在移动设备的本地存储中。
使用AsyncStorage.js
import React, { useEffect, useState } from 'react';
import AsyncStorage from '@react-native-community/async-storage';
export default function useAsyncStorage(key, defaultValue) {
const [storageValue, updateStorageValue] = useState(defaultValue);
useEffect(() => {
getStorageValue();
}, []);
async function getStorageValue() {
let value = defaultValue;
try {
value = (JSON.parse(await AsyncStorage.getItem(key))) || defaultValue;
} catch (e) {
// handle here
} finally {
updateStorage(value);
}
}
async function updateStorage(newValue) {
try {
await AsyncStorage.setItem(key, JSON.stringify(newValue));
} catch (e) {
// handle here
} finally {
getStorageValue();
}
}
return [storageValue, updateStorageValue];
}
在 App.js 中,我导入 useAsyncStorage.js 并尝试使用它将数据存储在移动设备的本地存储中。
import useAsyncStorage from './useAsyncStorage';
初始化它:
const [userLevel, setUserLevel] = useAsyncStorage("userLevel",1)
设置值:
setUserLevel(prevLevel => {
return prevLevel + 1
})
它按预期工作并设置数据,但在应用重新加载后无法从 AsyncStorage 中检索数据。
有人可以帮忙吗?我在 useAsyncStorage 自定义挂钩中做错了吗?为什么数据不存储在 AsyncStorage 中?
【问题讨论】:
标签: javascript reactjs react-native react-hooks asyncstorage