首页 > 解决方案 > 如何将函数设置为在另一个函数之后呈现?

问题描述

我将我的 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;

标签: reactjsfirebaseasynchronous

解决方案


正如 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>
    );
};

推荐阅读