javascript - 在应用程序加载时反应本机 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>
);
}
解决方案
缺少一些代码片段来全面了解到底发生了什么,但我想我还是明白了。所以你必须解决可用的策略:
- 使用同步存储解决方案,可以直接获取数据
- 异步获取数据,在加载时显示加载指示器或类似内容
使用同步存储解决方案
如果您能够安装本机依赖项,则可以安装一个用于同步数据访问的库,例如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>
}
有很多关于这个主题的教程,你可以谷歌。
推荐阅读
- javascript - 键入时 Ajax 脚本无法正常工作(keyup)
- oracle - 如何在sql server和Oracle中将列的当前值与同一列的先前值进行比较
- php - 如何在帖子列表页面中检索所有帖子的评论
- git - Fastlane 匹配无法通过 SSH 连接
- django - 如何在多对多关系中使用多项选择过滤对象
- html - Microsoft Outlook 条件格式问题
- firefox - 如何在 Firefox 中将 CSS 动画应用于 SVG 蒙版?
- logstash - jboss.logmanager 和 logstash 的自定义格式化程序
- css - `vp-preview-invisible` 类被添加到 Safari 中的预览缩略图中,但在 vimeo 嵌入视频中的 Chrome 中没有
- python - Python旋转密码脚本问题