繁体   English   中英

如何为每个 FaunaDB 文档生成单独的 NextJS 页面?

[英]How can I generate a separate NextJS page for each FaunaDB Document?

如何在子目录中的每个页面上生成不同的标题?

我的代码没有抛出任何错误,但不幸的是, Title组件在它应该呈现的每个页面上呈现每个title-item ,例如每个app.com/title/<title>呈现相同的视图(标题列表)。 我认为getStaticPaths是正确参数化的,但我不认为getStaticProps是。

export default function Title({ paper }) {

    // paper is just the entire dataset, and isn't split by id or author etc.

    return (
            <div>
                {paper.map(paper => (
                        <h1>{paper.data.title}</h1>
                ))}
            </div>
    )
}

export async function getStaticProps({ params }) {

    // ideally, results should be split down to e.g. `/api/getPapers/title`, but this didn't work

    const results = await fetch(`http://localhost:3000/api/getPapers/`).then(res => res.json());

    return {
        props: {
            paper: results
        }
    }
}

export async function getStaticPaths() {
    const papers = await fetch('http://localhost:3000/api/getPapers').then(res => res.json());

    const paths = papers.map(paper => {
        return {
            params: {
                authors: paper.data.title.toLowerCase().replace(/ /g, '-')
            }
        }
    })

    return {
        paths,
        fallback: false
    }
}

这是getPapers API function。

const faunadb = require("faunadb");

// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY;
const q = faunadb.query;
const client = new faunadb.Client({ secret });

module.exports = async (req, res) => {
  try {
    const dbs = await client.query(
      q.Map(
        // iterate each item in result
        q.Paginate(
          // make paginatable
          q.Match(
            // query index
            q.Index("all_research_papers") // specify source
          )
        ),
        (ref) => q.Get(ref) // lookup each result by its reference
      )
    );
    // ok
    res.status(200).json(dbs.data);
  } catch (e) {
    // something went wrong
    res.status(500).json({ error: e.message });
  }
};

您正在返回路径 object 中的authors 您需要确保您的页面文件以包含authors的方式命名。 例如:

app_directory
|- pages
  |- home.js
  |- title
    |- [authors].js

也许你在params object 中说authors的地方,你的意思是title 在这种情况下,重命名params object 和页面文件名。

    const paths = papers.map(paper => {
        return {
            params: {
                title: paper.data.title.toLowerCase().replace(/ /g, '-')
            }
        }
    })
app_directory
|- pages
  |- home.js
  |- title
    |- [title].js

这是getStaticPaths()的文档。 https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation

我为每个文档呈现单独页面的尝试缺少动态API 调用。 我只是希望使用单个(批处理文档)API 调用来呈现动态页面。

这是一个典型的动态 API 路由,称为[index.js]

const faunadb = require('faunadb')

// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY
const q = faunadb.query
const client = new faunadb.Client({ secret })

export default async (req, res) => {
  const {
    query: { index },
  } = req;

  try {
    const papers = await client.query(
      q.Get(q.Ref(q.Collection('<name of the collection>'), index))
    );
    res.status(200).json(papers.data);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
};


动态检索数据后,您可以设置动态页面路由,例如[id].js ,使用useSWR获取数据。

const { data, error } = useSWR(`/api/getPapers/${id}`, fetcher);

这是一个示例提取器 function:

const fetcher = (url) => fetch(url).then((r) => r.json());

就我而言,然后我可以使用调用{data.<field>}检索任何给定字段。

暂无
暂无

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

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