如何为react-native加载useState,其中包含来自异步存储的数据(不带null)

问题描述 投票:0回答:1

我需要使用本地存储中的值初始化我的 useState 。我无法让异步存储停止使所有内容异步。如果我使用 null 或随机默认值进行初始化,那么当承诺得到满足时,我会得到多次重新渲染,这会导致其他问题。我还尝试了 useAsuncStorage 它也只返回异步函数。我使用 cookies、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;


javascript reactjs react-native async-await asyncstorage
1个回答
1
投票

从本地存储获取数据只是异步的。您无法进行此同步。但是你可以添加额外的状态,比如 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
© www.soinside.com 2019 - 2024. All rights reserved.