如何在React Native中延迟渲染或在找到数据后进行渲染
所以我有一个关于如何在加载数据后在 React Native 中运行渲染的问题来自数据库。在我的代码中,我想列出处方,但它不断给出错误,因为它在执行到达 firebase 并获取处方数据的代码之前尝试在渲染函数中加载处方。我该如何做到这一点,以便在收集 Firebase 数据后进行渲染。
So I had a question about how to run rendering in react native after data is loaded from a database. In my code, I want to list prescriptions, but it keeps giving errors as it tries to load the prescription in the rendering function before executing the code that reaches out to firebase and gets the prescription data. How do I make it so that the rendering happens after the firebase data is gathered.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是在 React 中设置一个
loading
状态,该状态可以默认为true
,一旦从 Firebase 检索到数据,您就可以将其设置为 false。然后,在 jsx 中,您可以在加载状态为 true 时返回加载器或类似的内容,并且仅在 Firebase 数据可用且加载设置为 false 时才渲染依赖于 Firebase 数据的屏幕的其余部分。这是这个概念的最小演示:https://codesandbox .io/s/great-shockley-i6khsm?file=/src/App.js
如果您想进一步阅读并在 Firebase 函数失败时处理潜在的错误状态,那么这是一篇简洁的文章,可以避免具有加载、成功和错误状态的反模式。 https://dev.to/tehaisperlis/the-loading-anti-pattern- 7jj
The easiest way to do this is to just have a
loading
state in React, this can default totrue
and once the data has been retrieved from Firebase you set to false. Then in your jsx you can return a loader or similar while the loading state is true and only render the rest of the screen that relies on the Firebase data once it's available and loading is set to false. Here's a minimal demo of this concept:https://codesandbox.io/s/great-shockley-i6khsm?file=/src/App.js
If you want to read a bit further and handle a potential error state if the Firebase function fails then here's a neat article to avoid an anti-pattern having a loading, success and error state. https://dev.to/tehaisperlis/the-loading-anti-pattern-7jj
如果您查看此处的文档 (https://rnfirebase.io/firestore/usage)
这是
get()
示例这意味着您必须通过 async/await get() 此数据,因此请在下面执行此操作
If you look at the documentation here (https://rnfirebase.io/firestore/usage)
this is there
get()
exampleThis means that you have to get() this data through async/await so do this below