reactjs - 如何将函数设置为在另一个函数之后呈现?
问题描述
我将我的 React 应用程序连接到 Firebase,我认为问题是页面在从我的数据库中获取数据之前加载,我可以做些什么来延迟函数直到它完成获取数据之后?
function getPosts(){
db.collection("Posts").get().then(snapshot =>{
snapshot.docs.forEach(docs =>{
createPost(
docs.data().postName,
docs.data().createdAt,
docs.data().postContent,
)
})
})
}
getPosts();
function Blog(){
return (
<div>
<Navbar/>
<div className="container">
<div className="row" id="posts-collection">
</div>
</div>
</div>
)
}
export default Blog;
解决方案
正如 MehmetDemiray 已经展示的那样,您可以在函数组件中加载数据作为效果,但该答案假设您只希望跟踪加载状态。
如果您想使用加载的数据来显示发布数据,那么您还需要存储返回的数据。
const Blog: React.FunctionComponent = () => {
// state to store data returned by async call. (originally set to null).
const [posts, setPosts] = React.useState(null);
// use an effect to load async data.
// the effect only runs on component load and every time the data in
// the dependency array changes "[setPosts]" (reference comparison).
React.useEffect(() => {
// Create funtion to run async logic to load posts.
const getPosts = () => {
// load posts
db.collection("Posts").get().then(snapshot => {
// map loaded posts to an array of easy to manage objects.
const loadedPosts = snapshot.docs.map(docs => {
return {
name: docs.data().postName,
createdAt: docs.data().createdAt,
content: docs.data().postContent,
}
});
// store loaded posts in state.
setPosts(loadedPosts ?? []);
});
};
// run async function created above.
getPosts();
}, [setPosts])
// posts will remain null until the async function has loaded data.
// you can manually track loading in a separate state if required.
if (posts === null) {
// Show loading view while loading.
return (
<div>
Loading Posts...
</div>
);
}
// map out posts view after posts have been loaded.
return (
<div>
{posts.map(post => (
<div>
<div>{post.postName}</div>
<div>{post.createdAt}</div>
<div>{post.content}</div>
</div>
))}
</div>
);
};
推荐阅读
- ruby - ruby heredoc 和 sprintf escape %: throwing malformed format sting %" (ArgumentError)
- java - 我的禁令命令参数要求似乎不起作用(Bukkit)
- javascript - 如何在按钮单击时将类添加到具有相同名称的 div
- asp.net - ASP.NET Web 应用程序在本地运行,但在 Azure 上发布时显示错误
- flutter - Flutter IAP 在被取消后没有启动付款弹出窗口
- ssh - 是否可以重新启动 Colab ubuntu 机器?并使用相同的 ngrok 凭据重新 SSH 到它?
- json - 带有 SuperObject 的 JSON:元素是数组还是对象?
- c# - Windows 窗体富文本框如何移动选定的行?
- docker - Docker 不在浏览器中显示我的 codeigniter 应用程序
- spring-boot - 当我在 swagger-ui.html 中单击“试用”时,X-Forwarded-For 未出现