【发布时间】:2022-01-26 00:51:17
【问题描述】:
如何在子目录中的每个页面上生成不同的标题?
我的代码没有抛出任何错误,但不幸的是,Title 组件在它应该呈现的每个页面上呈现 every title-item,例如每个app.com/title/<title> 都会呈现 same 视图(标题列表)。我认为 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 函数。
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 });
}
};
【问题讨论】:
-
您是否创建了一个 API 路径来按标题从 FaunaDB 检索一篇论文?我想这就是你在这种情况下所需要的。另外,您不应该从
getStaticProps的内部API 路由中获取数据,直接使用逻辑即可。 -
我的 API 路由在一个批次中生成所有文档。是否有任何按参数获取文档的文档示例(即按标题的论文)?
-
可以分享一下
getPapersAPI 函数吗?papers可能是几件事,具体取决于您如何从 Fauna 返回结果。 -
@ptpaterson,我已经包含了上面的 API 函数。
-
@WΔ_,我已经根据API函数更新了答案
标签: javascript reactjs next.js faunadb