最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NextJS getStaticProps not passing returned props to page - Stack Overflow

programmeradmin1浏览0评论

I am having some issues getting my getStaticProps function to pass the returned props into template pages in NextJS.

Here is the code I currently have for the dynamic page template.

// src/pages/blog/[slug].js
import React from 'react';
import matter from 'gray-matter';
import ReactMarkdown from 'react-markdown';

import Layout from '../../ponents/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,
    }
}

When running the site, the page just doesn't load, and throws the same console logged error in the main window.

I have another site set up in exactly the same way and I have absolutely no issues, so I am struggling to understand why the props being returned from getStaticProps are not being passed into the function to build the page.

Any assistance would be greatly appreciated!

Update

This is the error log when piling the site.

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)

Update #2

Here is the contents of the markdown file.

// src/posts/first-post.md

---
title: first post

---

This is a basic first post

I am having some issues getting my getStaticProps function to pass the returned props into template pages in NextJS.

Here is the code I currently have for the dynamic page template.

// src/pages/blog/[slug].js
import React from 'react';
import matter from 'gray-matter';
import ReactMarkdown from 'react-markdown';

import Layout from '../../ponents/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,
    }
}

When running the site, the page just doesn't load, and throws the same console logged error in the main window.

I have another site set up in exactly the same way and I have absolutely no issues, so I am struggling to understand why the props being returned from getStaticProps are not being passed into the function to build the page.

Any assistance would be greatly appreciated!

Update

This is the error log when piling the site.

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)

Update #2

Here is the contents of the markdown file.

// src/posts/first-post.md

---
title: first post

---

This is a basic first post
Share Improve this question edited Dec 11, 2020 at 9:38 nickwarters asked Dec 11, 2020 at 8:55 nickwartersnickwarters 1431 silver badge7 bronze badges 9
  • could you provide the error log? – Quang Thái Commented Dec 11, 2020 at 8:57
  • @nickwarters de-structuring is incorrect .. should be getStaticProps({params}){ const {slug} = params;} – Nilesh Patel Commented Dec 11, 2020 at 9:02
  • @NileshPatel Changing this did not fix the issue. The returned props are still not passed to the page template. – nickwarters Commented Dec 11, 2020 at 9:09
  • @QuangThái I have updated with the error log – nickwarters Commented Dec 11, 2020 at 9:12
  • @nickwarters this is different issue now.. const data = matter(content.default) is not returning title property.. please check md file posts/${slug}.md – Nilesh Patel Commented Dec 11, 2020 at 9:16
 |  Show 4 more ments

1 Answer 1

Reset to default 9

Issue seemed to be due to not passing {...pageProps} in the _app.js file. See code below:

Previous code:

import '../styles/main.scss'

export default function MyApp({ Component, pageProps }) {
  return <Component />
}

New code which piles correctly:

import '../styles/main.scss'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>