额外的键是从`getServerSideProps` 返回的。从 getServerSideProps

时间:2021-04-01 20:33:44

标签: reactjs next.js

我有下一个应用程序。当路由在 [slug] 页面中不匹配时,我需要实现逻辑然后显示 404 页面错误。

接下来,据我所知,对于显示 404 页面,我需要返回值为 notFoundtrue 对象。Link

问题是当我从 { notFound: true } 返回 getServerSideProps 时,为什么会出现此错误?

<块引用>

错误:从 getServerSideProps 返回了其他密钥。 用于组件的属性必须嵌套在 props 键,例如:

return { props: { title: 'My Title', content: '...' } }

需要移动的键:notFound。

代码:

export const getServerSideProps: GetServerSideProps = async ({ params, req }) => {

    const { slug } =  params;

    // first request
    const data = await (await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/${slug}`)).json();

    // second request
    const user = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}`, {
        method: "GET",
        headers: {
            'Authorization': 'Bearer ' + "jwt",
            'Content-Type': 'application/json',
        },
    });
    const userInfo = await user.json();


    if ( !slug || data.statusCode === 404 ) return { notFound: true }

    return {
        props: {
            title: "something",
            // my props in here
        },
    }
}

仅当我在 url 中写一些东西并有意识地将我的 slug 页面从正确更改为不正确时,它才会出错。例如从 localhost/page/1localhost/page/blablabla

在这种情况下,当我将路由更改为错误时,如果 case (if ( !slug || data.statusCode === 404 ) ).Next version 9.5.2

1 个答案:

答案 0 :(得分:2)

您使用的是 Next 版本 9.5.2。支持 notFound 的最早版本是 10.0.0。来自docs

>v10.0.0 locale, locales, defaultLocale, and notFound options added.

因此您必须升级才能使用该逻辑。