簡體   English   中英

使用 React Js 獲取 Firebase 實時數據庫

[英]Fetching in Firebase Realtime Database with React Js

使用 react js 掛鈎在 firebase 實時數據庫上獲取數據時出現錯誤。 當我使用 map 刪除數據時,出現“未定義”錯誤,但我在控制台日志數據中看到成功。

我認為錯誤是因為循環代碼在獲取完成之前執行

這是獲取代碼

    const [firebaseDb, setFirebaseDb] = useState(database);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);

    const getData = async () =>{
        try {
            const dbRef = firebaseDb;
            let snapshot = await get(child(dbRef, `menu`))
            if (snapshot.exists()) {
                console.log(snapshot.val());
                setData(snapshot.val());
                setLoading(false);
            } else {
                setData({});
                setLoading(false);
                console.log("No data available");
            }
        } catch(e){
            setLoading(false)
            console.log(e.message);
                        
        }        
        
    } 

    useEffect(() => {
        setLoading(true);
        getData()
    }, []);

這是亂碼

            {
                loading ? (
                    <Row><p>Loading ... !</p></Row>

                ) : (
                        <Row>
                            {
                                data.appetizer.map((apper, index) => {
                                    return (
                                        <Col key={index} lg='6' className="p-3">
                                            <div className="menu-list p-3">
                                                <h5>{apper.name}</h5>
                                                <h4>{apper.price}k</h4>
                                                <p className="mb-0">{apper.desc}</p>
                                            </div>
                                        </Col>
                                    )
                                })
                            }
                        </Row>
                    )

            }

您的data變量最初是一個數組,因此它沒有appetizer屬性。 改用data.map(...) (嘗試使用數組傳遞給setData

當然,渲染將始終在獲取完成之前執行。 您只需要在渲染映射之前檢查typeof data.length > 0 ---- 或者只是將loading的初始值設置為 true。

它應該是這樣的:

const [loading, setLoading] = useState(true);

或者

loading || data.length === 0 ? (
    <Row><p>Loading ... !</p></Row>
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM