首页 > 解决方案 > 使用动态路由部署 Next JS 应用程序时出错

问题描述

我最近使用 Next JS 完成了个人博客的 Next JS 应用程序,但每次点击npm run-script build它都会显示动态路由错误。

如下所示的动态路由页面的代码

import cateogaryPage from '../../styles/cardsPage.module.scss'
import cx from 'classnames'
import data from '../../FakeData/index.json'
import fakeLinks from '../../components/DataFetching/index'
import CardsPage from '../../components/Card Page/Cards Page';
import SeoOptimised from '../../components/Seo/index'

export const getStaticProps = async (context) => {
    const { cateogary } = context.params;
    const getTheCateogariesRes = await fetch(`API to get the particular posts with the particular category`)
    const getTheCateogaries = await getTheCateogariesRes.json()

    return {
        props: {
            getTheCateogaries,
        }
    }
}


export const getStaticPaths = async () => {
    const getTheCateogariesRes = await fetch(`API to get all the Categories`)
    const getTheCateogaries = await getTheCateogariesRes.json()


    const CateogariesOnly = getTheCateogaries.map(cateogary => cateogary.Cateogary)
    const paths = CateogariesOnly.map(CateogaryBlock => ({ params: { cateogary: CateogaryBlock.toString() } }))
    console.log(paths[0])


    // const Headlines = articles.map(article => article.Headline)
    // const paths = Headlines.map(Headline => ({ params: { post: Headline.toString() } }))

    return {
        paths,
        fallback: true
    }
}

export default function cateogaryPageFun({ getTheCateogaries }) {
    let cateogaryHead = String('contextVariable');
    return (
        <>
            <SeoOptimised curPage={String(cateogaryHead).charAt(0).toUpperCase() + String(cateogaryHead).slice(1)} />
            <div className={cx(cateogaryPage.w3lhomeblock2, cateogaryPage.py5)}>
                <div className={cx(cateogaryPage.container, cateogaryPage.ptmd4, cateogaryPage.pbmd5)}>
                    {/* block */}
                    <h1 className={cx(cateogaryPage.categorytitle, cateogaryPage.mb3)}> {String(cateogaryHead).charAt(0).toUpperCase() + String(cateogaryHead).slice(1)}</h1>
                    <p className={cx(cateogaryPage.mbmd5, cateogaryPage.mb4, cateogaryPage.maxwidth, cateogaryPage.CustomP)}>Cateogarised Blog Post from {data.name}. Showing Results for {cateogaryHead}</p>
                    <div className={cateogaryPage.row}>
                        {getTheCateogaries.map((blog) => {
                            return <CardsPage key={blog.id} PostContent={blog.Content} image={blog.Image} PostHead={blog.Headline} PostName={blog.Headline} date={blog.date} time={blog.Time} />
                        })}
                    </div>
                    {/* <ul className="site-pagination text-center mt-md-5 mt-4">
                    <li><span aria-current="page" className="page-numbers current">1</span></li>
                    <li><a className="page-numbers" href="#page2">2</a></li>
                    <li><a className="page-numbers" href="#page3">3</a></li>
                    <li><span className="page-numbers dots">…&lt;/span></li>
                    <li><a className="page-numbers" href="#page7">7</a></li>
                    <li><a className="next page-numbers" href="#next">Next »</a></li>
                </ul> */}
                </div>
            </div>
        </>
    )
}

每次我运行npm run-script build它都会显示这个错误:

Error occurred prerendering page "/posts/[post]". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read property 'Headline' of undefined
    at BlogPost (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\.next\server\pages\posts\[post].js:741:32)
    at d (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:33:498)
    at bb (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:36:16)
    at a.b.render (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:42:43)    
    at a.b.read (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:41:83)      
    at exports.renderToString (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\next\dist\next-server\server\render.js:54:854)
    at Function.getInitialProps (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\.next\server\pages\_document.js:603:19)
    at loadGetInitialProps (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\next\dist\next-server\lib\utils.js:5:101)
    at renderToHTML (D:\Web Developement\Next Projects\BlogX\Down the Code\downthecode\node_modules\next\dist\next-server\server\render.js:54:1145)

但我不知道错误是什么,因为每当我点击 URL 时,我都会在响应中得到这些:

这是一个特定的 API 被 codenewbie 击中的时候


  {
    "id": 1,
    "Image": "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzegd2hhujof2kx2hg0r.jpg",
    "Hashtag": "python",
    "Hashtag2": "codenewbie",
    "Hashtag3": "computerscience",
    "Hashtag4": "webdev",
    "Headline": "Getting Started with Programming",
    "Content": "Steve Jobs once said, “Everybody in this country should learn how to program a computer… because it teaches you how to think.”\r\n\r\nComputer Program is a skill with the help of which you an do amazing things which are either one of them. It can be Hard Labor or Impossible(Some times). We Humans are surrounded by Programs only, either be it Opening you Phone or Switching Your WiFi On/off, or be it Listening to a Music on Spotify or other things. There are tons of different activities which involves Computer Program.\r\n\r\nWhile surrounded by tons of Computer Programs. What if Persons Like Me and You Starts to Controlling These Programs on our Will??\r\n\r\nBy learning Programming Doesn't mean that You got the Responsibility of Creating Next Facebook or Next Google. It Just mean That you have the Ability to create the next. But as a Famous Quote says That History is never made by doing sort of planning or Without Planning. You Just have to get the guts to do that. and that's all. You just have to learn any one Programming Language and that's all you can Automate any thing In it and can Create some Best Apps That might can Change The World.\r\n\r\nThere are Three Major Reason For Learning Programming. All of them are Listed Below :-\r\n\r\n# 1. Coding develops structured and creative thinking\r\n\r\n\r\nWhen a Programmer is given a Problem to solve, They Just don't Open Their Code - Editor and Start Coding. Coding is never done in That way. But Instead The Programmers always try to break a Particular task into simple and small blocks in which they can code as a Checkpoint.\r\nDo Ever A Non - Programmer will approach like in this way ?? Its Rare!! By learning Programming The Programmer always Train / Program their Brain to Do a Specific Task for Each and Every programming Question\r\n\r\n  - Break the Program into Small Pieces\r\n  - Find The Creative Way to Do that task\r\n  - Integrate different Block and Test it Weather the main Block is Running Every Block or Not\r\n  - Kaboom !!! You Just Created The Program\r\n\r\n# 2. Programming makes things easier for you\r\n\r\n\r\nA simple computer program is capable of turning things around as you want. Something that works on pushing buttons can be programmed to do so on a tap on your smartphone or when you double clap. Yeah, you can switch on/off your electrical appliances using your smartphones.\r\nSomething that requires your input repeatedly, just like the online forms where you have to fill your First Name, Second Name, Email and other information, can be programmed to have your opinion once and it could literally fill out your forms with a single click. Yes, it’s possible. Something as simple as working on Excel Sheets can make you go crazy because of the manual labor it requires. You can write little programs to help yourself.\r\n\r\n<br>\r\n\r\nFor Example Lets Suppose you have a task on Excel Sheet to add the contents of column 2, 3 and 4, and then find the average of the result. If you have to do this task multiple times in a day, every day, it would be chaotic. Right? Now, if you write a small program that can perform these functions all at once, you’ll be saving your time, effort and you’ll be 100 times more efficient.\r\nEver tried playing Chess on your smartphone. How is it that a lifeless being, I mean, your smartphone is smarter than you? It is programmed that way. It is programmed to make right moves on every move that you can possibly take while playing Chess. The same case exists with any smartphone game or desktop game. With programming skills, you can create your own tools and make your life simple.\r\n\r\n# 3. Learning to program teaches you persistence\r\n\r\n\r\nWhen you learn computer programming, you start seeing problems in the light of solutions. Your brain starts functioning like that. When you encounter a problem after learning to program, you start envisioning the possible ways to solve it. You may even foresee some good results out of it. However hard the problem might seem, you become determined to act on it anyhow. You transform yourself into a solution-driven individual.\r\n\r\n<br>Programmers have to think logically about a problem. Once you start learning how to code, you stop giving up on other difficult situations in your day-to-day life as well. You start trying over and over again. You become patient because you know there is always a solution. It just needs some more effort, just like it happens when you create a program, runs it, and debug it several times to reach the perfect solution. Computer programming is powerful. Even if you know just the basics of programming, you can imagine a lot of solutions and can work to solve your (and maybe the world’s) problems. Learn computer programming to feel the confidence of having this robust tool at your disposal. It’s amazing!\r\n\r\nSee you next week in a new Post.",
    "Cateogary": "codenewbie",
    "date": "2021-05-27",
    "Time": "11:45:43",
    "Likes": 0,
    "Times_Opened": 22
  }
]

这是我想要获得所有类别来构建静态页面的时候

[
  {
    "id": 1,
    "Cateogary": "codenewbie",
    "Times_Opened": 26
  },
  {
    "id": 2,
    "Cateogary": "Operating System",
    "Times_Opened": 15
  }
]

身体请帮我解决这个问题

标签: javascriptreactjsapideploymentnext.js

解决方案


如果您的文件名是 /posts/[post].js ,那么您在 getStaticPaths 中的参数应该是

params: { post : CateogaryBlock.toString() }

推荐阅读