【发布时间】:2020-11-02 16:48:15
【问题描述】:
我的 [slug].js 文件如下,有两个 nextjs 辅助函数。 getStaticPaths 和 getStaticProps 被导出。在我的例子中,它创建了路径posts/[slug]。添加了一个名为hello.json 的帖子文件。现在,当我导航到 localhost:3000/posts/hello 时,它会出错:
TypeError: Cannot read property 'fileRelativePath' of undefined。对于第 10 行。
看到jsonFile 未定义后,这才有意义。事实上,整个getStaticProps 永远不会被调用,那里的登录永远不会被记录。为什么会这样?
提前致谢。
import React from 'react';
import glob from 'glob';
import { usePlugin } from 'tinacms';
import { useJsonForm } from 'next-tinacms-json';
const Page = ({ jsonFile }) => {
console.log(121212, jsonFile);
// Create the tina form
const [post, form] = useJsonForm(jsonFile);
// Register it with the CMS
usePlugin(form);
return (
<h1>
{post.title}
</h1>
);
};
export default Page;
/**
* By exporting the async function called getStaticProps from a page, Next.js
* pre-renders this page at build time using the props returned by
* getStaticProps.
* The getStaticPaths function defines a list of paths that have
* to be rendered to HTML at build time.
*/
export async function getStaticProps({ ...ctx }) {
console.log(1212, ctx);
const { slug } = ctx.params;
const dynamicPath = `../../posts/${slug}.json`; // for eslint parsing error: "Cannot read property 'range' of null Occurred while linting"
const content = await import(dynamicPath);
console.log(121212, content);
return {
props: {
jsonFile: {
fileRelativePath: `/posts/${slug}.json`,
data: content.default,
},
},
};
}
export async function getStaticPaths() {
//get all .json files in the posts dir
const posts = glob.sync('posts/**/*.json');
const paths = posts.map(file => ({
params: {
slug: `${file.replace('.json', '')}`,
},
}));
return {
paths,
fallback: true,
};
};
【问题讨论】:
-
你试过
export async function getStaticPaths而不是export const getStaticPaths = async () -
是的,这没有任何区别。 getStaticPaths 似乎完成了它的工作。将编辑答案以使两个功能一致
标签: javascript reactjs next.js