我在让我的 getStaticProps 函数将返回的道具传递到 NextJS 中的模板页面时遇到了一些问题。
这是我目前用于动态页面模板的代码。
// src/pages/blog/[slug].js
import React from 'react';
import matter from 'gray-matter';
import ReactMarkdown from 'react-markdown';
import Layout from '../../components/layout';
export default function BlogPost ({frontmatter, markdownBody}){
console.log(`in template Layout: ${frontmatter.title}`)
// Output: TypeError: Cannot read property 'title' of undefined
return (
<Layout>
<h1>{frontmatter.title}</h1>
<span>{JSON.stringify(markdownBody)}</span>
</Layout>
)
}
export async function getStaticProps({...ctx}){
const {slug} = ctx.params;
console.log(slug)
// output: first post (this is correct)
const content = await import(`../../posts/${slug}.md`)
const data = matter(content.default)
console.log(`In getStaticProps: ${data.data.title}`)
// output: In getStaticProps: first post (this is correct too)
return {
props: {
frontmatter: data.data,
markdownBody: data.content
},
};
}
export async function getStaticPaths(){
const postSlugs = ((context) => {
const keys = context.keys()
const data = keys.map((key, index) => {
let postSlug = key.replace(/^.*[\\/]/, "").slice(0,-3)
return postSlug
})
return data
})(require.context("../../posts/", true, /\.md$/))
const paths = postSlugs.map((postSlug) => `/blog/${postSlug}`)
return{
paths,
fallback: false,
}
}
运行该站点时,该页面不会加载,并在主窗口中引发相同的控制台记录错误。
我有另一个网站以完全相同的方式设置,我绝对没有问题,所以我很难理解为什么从 getStaticProps 返回的道具没有被传递到构建页面的函数中。
任何帮助将不胜感激!
更新
这是编译站点时的错误日志。
TypeError: Cannot read property 'title' of undefined
at BlogPost (webpack-internal:///./src/pages/blog/[slug].js:24:50)
at processChild (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/react-dom/cjs/react-dom-server.node.development.js:3353:14)
at resolve (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5)
at ReactDOMServerRenderer.render (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22)
at ReactDOMServerRenderer.read (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29)
at renderToString (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/react-dom/cjs/react-dom-server.node.development.js:4298:27)
at Object.renderPage (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/next/dist/next-server/server/render.js:53:851)
at Function.getInitialProps (webpack-internal:///./node_modules/next/dist/pages/_document.js:135:19)
at loadGetInitialProps (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/next/dist/next-server/lib/utils.js:5:101)
at renderToHTML (/Users/nick/dev/Web/templates/nextjs/simple-blog-template/node_modules/next/dist/next-server/server/render.js:53:1142)
更新#2
这是降价文件的内容。
// src/posts/first-post.md
---
title: first post
---
This is a basic first post