簡體   English   中英

無法使用 nextjs 從 firestore 讀取數據

[英]Failing to read data from firestore using nextjs

我正在嘗試在 nextjs 上使用 getStaticprops 從 firestore 讀取數據,但我得到的是一個空頁面。 我遵循了有關如何使用 getStaticprops 提取數據的文檔,但由於某種原因,它不起作用。 這就是我的代碼的樣子

import React from 'react'
import { db } from '../firebase'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");

export const getStaticProps = async () => {
    const data = await getDocs(reference);
    const students = data.docs.map(doc => ({...doc.data(), id: doc.id}));

    return {
        props: {
           students
        }
    }
}

function Card({students = []}) {
    return (
        <div>
        <p>This is just a test</p>
        {students.map(student => (
            <h1>{student.surname}</h1>
        ))}
    </div>
  )
}

export default Card

我哪里會出錯?

經過一些分析和嘗試示例代碼,這里是我的理解。

getStaticProps僅用於靜態站點生成。 IE。 如果您的頁面始終呈現相同的數據(您從 api 獲取的數據),那么您可以使用 getStaticProps。

例如,在您的情況下,您使用靜態道具定義了Card組件。 該組件將有一條路線說/Card

當您運行next build時,數據將從服務器獲取並用於該頁面。 然后npm start 當您訪問/Card路線時,此數據將可用。(注意:getStaticProps 只會在構建時調用)

但是如果你從其他頁面調用相同的組件,那么靜態道具將不會被認為你必須提供自己的道具,比如

<Card students={[]} />

如果您想在頁面呈現時獲取學生數據,請在 useEffect() 中調用 api。

注意:getStaticProps 只會在構建時調用,這就是為什么您沒有在控制台中獲得任何 console.log() 的原因。它將在構建站點時被記錄下來。

在 firebase 文檔示例中,( https://firebase.google.com/docs/firestore/query-data/get-data#web-version-9_6 )

響應用作數組 (data.forEach)。但在您的代碼中,您像訪問對象 (data.docs) 一樣訪問它。

你能試試這個嗎

const students = data.map(doc => ({...doc.data(), id: doc.id}));

暫無
暫無

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

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