如何从React-native的非空存储中加载useState数据

2sbarzqh  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(98)

我需要使用本地存储的值初始化我的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;

字符串

2g32fytz

2g32fytz1#

从localstore中获取数据只是一个错误。你不能进行这种同步。但是你可以添加额外的状态,比如prop isLoading或类似的东西。你可以停止渲染或显示加载图标或任何你喜欢的东西。

const [postFilterType, setPostFilterType] = useState("trending");
const [postModeType, setPostModeType] = useState("home");
const [isLoading, setLoading] = useState(true);

AsyncStorage.getItem('postFilterType').then(r => setPostFilterType(r));
AsyncStorage.getItem('postModeType').then(r => setPostModeType(r));

// your updateMethods

return {
   isLoading, 
   postFilterType
   postModeType,
   updatePostFilterType,
   updatePostModeType 
}

字符串
在您的组件中

const {isLoading} = usePostFilterOptions();

if (isLoading) {
   return <div>Loading...</div>;
   // or
   return;  // stop rendering the component, and wait until data is fetched.
}

// render component here

相关问题