首页 > 解决方案 > 在应用程序加载时反应本机 AsyncStorage 访问

问题描述

我需要在打开应用程序时立即从 AsycStorage 访问数据以传递给我的功能之一 WidgetGenerator。但是,似乎没有办法调用getData()并等待它设置 的值initVals,它只是继续按顺序执行代码WidgetGenerator()并传递undefined给它返回的组件,因为getData()尚未返回。此外,当我将 WidgetGenerator 设为异步函数时,它似乎并不喜欢它。我该怎么做才能在加载时访问 AsyncData?

const getData = async () => {
        try {
            const jsonValue = await AsyncStorage.getItem('@1629349495937')
            if (jsonValue != null) {
                //console.log(JSON.parse(jsonValue));
                initVals = JSON.parse(jsonValue);
            }
        } catch(e) {
            // error reading value
        }
    }
    function WidgetGenerator(props) {
        
        switch (props.args[0]) {
            case "heading":
                return <UIComponents.UIHeading
                            text={props.args[1]}
                            id={props.id}
                            init={initVals ? initVals[props.id] : undefined}
                        />;
            case "checkbox":
                return <UIComponents.UICheckbox
                            text={props.args[1]}
                            id={props.id}
                            callback={props.callback}
                            init={initVals ? initVals[props.id] : undefined}
                        />;
        }
        
        return <View />;
    }
    
    return (
        <View>
            {widgetArray.map((data, index) => <WidgetGenerator key={index} id={index} args={data} callback={collectData}/>)}
            <UIComponents.UISubmitButton callback={submitData} />
        </View>
        
    );

}

标签: javascriptreact-nativeasync-awaitasyncstorage

解决方案


缺少一些代码片段来全面了解到底发生了什么,但我想我还是明白了。所以你必须解决可用的策略:

  1. 使用同步存储解决方案,可以直接获取数据
  2. 异步获取数据,在加载时显示加载指示器或类似内容

使用同步存储解决方案

如果您能够安装本机依赖项,​​则可以安装一个用于同步数据访问的库,例如react-native-mmkv。只需浏览其文档,应该很简单。

异步加载数据

有很多方法可以做到这一点。理想情况下,您在应用程序启动时加载您的应用程序数据,同时显示启动屏幕,并将数据存储在全局存储中(可以像 JS 对象一样简单),因此您可以在运行时直接访问它们。但是,react 中异步数据加载的一般模式如下所示:

function Component() {
  const [data, setData] = useState();
  const [isError, setIsError] = useState(false);

  // load the data
  useEffect(() => {
    const asyncAction = async () => {
      try {
        const _data = await getData();
        setIsError(false);
        setData(data);
      } catch (e) {
        setIsError(true);
      }
    }
  }, []);

  if (isError) {
    return // view indicating an error
  }

  if (data == null) {
   return // view indicating loading
  }

  return <View>{/* actual implementation that is using data*/}</View>
}

有很多关于这个主题的教程,你可以谷歌。


推荐阅读