【问题标题】:Additional keys were returned from `getServerSideProps`. Return notFound object from getServerSideProps从 `getServerSideProps` 返回了额外的密钥。从 getServerSideProps 返回 notFound 对象
【发布时间】:2021-06-28 20:20:20
【问题描述】:

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

据我所知,在接下来的显示 404 页面中,我需要返回值为 true.LinknotFound 对象

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

错误:从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

在这种情况下,当我将路线更改为错误时,如果情况 (if ( !slug || data.statusCode === 404 ) ).Next 版本 9.5.2,则可以这样做

【问题讨论】:

  • 你确定这是给你一个错误的代码吗?它看起来不错,除了奇怪的等待,但它应该按预期工作。您使用的是哪个版本的 Next?
  • @Danila 只有当我在 url 中写一些东西并有意识地将我的 slug 页面从正确更改为不正确时,它才会出错。例如从localhost/page/1localhost/page/blablabla。在这种情况下,当我将路由更改为错误时,如果情况(if ( !slug || data.statusCode === 404 ) ). 下一个版本9.5.2。更新答案

标签: reactjs next.js


【解决方案1】:

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

所以你必须升级才能使用该逻辑。

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 2022-08-04
    • 2021-06-23
    • 1970-01-01
    • 2021-05-14
    • 2021-12-08
    • 2023-02-12
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多