简体   繁体   English

无法使用 nextjs 中的 getStaticPaths 从 firestore 获取动态数据

[英]Failing to fetch dynamic data from firestore using getStaticPaths in nextjs

When I fetch data from firebase firestore using getStaticProps, it works perfectly but when I try implementing the logic of getting the details of each single item using getStaticPaths, I fail and get a 404 page.当我使用 getStaticProps 从 firebase firestore 获取数据时,它工作得很好,但是当我尝试实现使用 getStaticPaths 获取每个单个项目的详细信息的逻辑时,我失败并获得 404 页面。 This is how my [id].js code looks like currently.这就是我的 [id].js 代码目前的样子。

import React from 'react'
import { db } from '@/Firebase';
import {collection, getDoc} from "firebase/firestore";

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

export const getStaticPaths= async () => {
    const umuntu = await getDoc(reference);

    const paths = umuntu.docs.map(doc => {
        return {
            params: { id: doc.id }
        }
    })

    return {
        paths,
        fallback: false
    }

}

export const getStaticProps = async (context) => {
    const id = context.params.id;
    const data = await getDoc(reference) + id;
    
    return {
        props: {
            umuntu: data
        }
    }
}

function Details({umuntu}) {
  return (
    <div>
        <h1>{umuntu.ibizo}</h1>
    </div>
  )
}

export default Details

I dont quite get where my logic is going wrong but where could I be going wrong?.我不太明白我的逻辑哪里出了问题,但我哪里会出错?

For finding the right page props for each of the paths that you generate from the database in the getStaticPaths function, you should be able to find each of the pages information based on the id field you are getting from each path, see it here:为了在getStaticPaths function 中为从数据库生成的每个路径找到正确的页面道具,您应该能够根据从每个路径获取的id字段找到每个页面信息,请在此处查看:

export const getStaticProps = async (context) => {
  const id = context.params.id;
  const umuntu = await getDoc(reference);
  const data = umuntu.docs.find((pageData) => pageData.id === id); // this will find the right page based on the id passed via page path

  return {
    props: {
      data
    },
  };
};

function Details({ data }) {
  return (
    <div>
      <h1>{data.ibizo}</h1>
    </div>
  );
}

export default Details;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM