【发布时间】:2022-01-31 01:50:11
【问题描述】:
我无法在 Next.js/React 项目中调用 getStaticProps 函数。我想在页面路径更改为/blog 时加载getStaticProps 所以在我的pages/blogs 中
type BlogStaticInputs = {
blogs: BlogsType[]
}
export const getStaticProps: GetStaticProps = async () => {
console.log('hello')
const blogs = getAllBlogs(['date', 'slug', 'title'])
return {
props: { blogs }
}
}
export const Index = ({ blogs }: BlogStaticInputs) => {
return <Blogs blogs={blogs} />
}
export default Index
而我的BlogType 是
export type BlogType = {
date?: string
slug: string
title: string
}
而且我在控制台中看不到console.log('hello'),所以我认为getStaticProps 目前没有工作。
在我的_app.tsx - 我认为这是正确加载道具和组件。
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
</>
)
}
export default MyApp
而我的getAllBlogs 看起来像这样
export function getAllBlogs(fields: string[] = []): BlogItems[] {
console.log('I am getting blogs now...')
const slugs = getBlogSlugs()
const posts = slugs
.map((slug) => getBlogBySlug(slug, fields))
// sort posts by date in descending order
.sort((post1, post2) => (post1.date > post2.date ? -1 : 1))
return posts
}
和支持的功能就是这些。
export function getBlogSlugs(): string[] {
return fs.readdirSync(POSTS_PATH)
}
type BlogItems = {
[key: string]: string
}
export function getBlogBySlug(slug: string, fields: string[] = []): BlogItems {
const realSlug = slug.replace(/\.mdx$/, '')
const fullPath = join(POSTS_PATH, `${realSlug}.mdx`)
const fileContents = fs.readFileSync(fullPath, 'utf8')
const { data, content } = matter(fileContents)
const items: BlogItems = {}
// Ensure only the minimal needed data is exposed
fields.forEach((field) => {
if (field === 'slug') {
items[field] = realSlug
}
if (field === 'content') {
items[field] = content
}
if (data[field]) {
items[field] = data[field]
}
})
return items
}
以及获取博客目录路径的支持功能
export const POSTS_PATH = path.join(process.cwd(), 'blogs')
我认为 getAllBlogs 函数尚未调用,因为我看不到 console.log('I am getting blogs now...')。
【问题讨论】:
-
getAllBlogs 函数是什么样子的?
-
我添加了
getAllBlog函数!在调用`return之前,我尝试在我的 export const Index函数中使用console.log(blogs),参数博客仍然是空的 -
确保以下几点: 1) 确保
getStaticProps是从页面组件(pages文件夹下的组件)导出的; 2) 检查您启动开发服务器的终端是否有getStaticProps内的任何console.logs -getStaticProps在服务器上运行,因此这些不会出现在浏览器的控制台中。
标签: reactjs typescript next.js