我需要使用本地存储的值初始化我的useState。我不能让useState-storage停止使所有内容都是useState。如果我使用null或随机默认值初始化,那么当promise得到满足时,我会得到多个重新呈现,这会导致其他问题。我还尝试了useAsuncStorage,它也只返回useState函数。我有相同的代码,使用cookie和react编写-Cookie和useCookie和没有任何问题。大家有什么建议吗?
import { useEffect, useState } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
const usePostFilterOptions = () => {
const getPostFilterType = async () => {
const savedPostFilterType = await AsyncStorage.getItem('postFilterType') ?? 'trending';
return savedPostFilterType;
}
const getPostModeType = async () => {
const savedPostModeType = await AsyncStorage.getItem('postModeType') ?? 'home';
return savedPostModeType;
}
const [postFilterType, setPostFilterType] = useState(getPostFilterType());
const [postModeType, setPostModeType] = useState(getPostModeType());
const updatePostFilterType = async (type) => {
await AsyncStorage.setItem('postFilterType', type);
setPostFilterType(type);
}
const updatePostModeType = async (type) => {
await AsyncStorage.setItem('postModeType', type);
setPostModeType(type);
}
return { postFilterType, updatePostFilterType, postModeType, updatePostModeType };
};
export default usePostFilterOptions;
字符串
1条答案
按热度按时间2g32fytz1#
从localstore中获取数据只是一个错误。你不能进行这种同步。但是你可以添加额外的状态,比如prop
isLoading
或类似的东西。你可以停止渲染或显示加载图标或任何你喜欢的东西。字符串
在您的组件中
型