firebase 组件显示错误消息,然后呈现页面

zdwk9cvp  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(92)

我有一个呈现酒店信息列表组件:

import {useEffect, useState} from "react";
import {onSnapshot} from "firebase/firestore"
import {hotelCollection} from "../controller/controller";
import {HotelType} from "../types/hotel";
import Information from "../components/Information";

function Card() {

    const [isLoading, setIsLoading] = useState(false);
    const [hotels, setHotels] = useState<HotelType[]>([]);

    useEffect(() => onSnapshot(hotelCollection, (snapshot) => {
        setIsLoading(true);
        setHotels(
            snapshot.docs.map((doc) => {
                return {
                    id: doc.id,
                    ...doc.data(),
                }
            })
        )
        setIsLoading(false);
    }), []);

    if (isLoading) return <div className="loading"/>;
    return (
        <div className={"card"}>
            <h2 className="title">All hotels</h2>
            {hotels && hotels.length ? (
                <div>
                    {
                        hotels?.map((hotel) => (
                            <Information key= {hotel.id} hotel={hotel}/>
                        ))
                    }
                </div>
            ): (
                <h2 className="no-hotels">There isn't any hotel, please add one.</h2>
            )}
        </div>
    )
}

export default Card;

一切正常,只是当我进入页面或通过路径访问页面时,它首先显示

<h2 className="no-hotels">There isn't any hotel, please add one.</h2>

然后呈现组件
我不知道为什么,有人能帮忙吗?

py49o6xq

py49o6xq1#

根据我收到的评论,我没有将“isLoading”初始化为false,而是将其设置为true,

const [isLoading, setIsLoading] = useState(true);

然后我删除了这一行:

setIsLoading(true); // removed

并没有触及其余的代码。
已经解决了

相关问题