繁体   English   中英

动态路由防止重定向到 Next.js 中的 404 页面

[英]Dynamic route prevents redirecting to 404 page in Next.js

我的 Next.js 项目中有一个[pid].js文件。 我也想实现自定义 404 页面,但问题是:我将404.js文件放在/pages目录中。 如果我删除我的[pid].js文件,404 页面就可以正常工作。 但是,如果我保留我的[pid].js文件,第一个请求进入 pids,并且由于 url 与 pids 中定义的任何页面都不匹配,我得到一个错误。 我应该明确地从 pids 返回我的 404 组件吗? 这是一个好习惯吗?

这是代码(现在不会重定向到 404 页面):

[pid].js

const Pid = ({ url, props }) => {
    const getPages = () => {
        let component = null;
        switch (url) {
            case 'checkout':
                component = <CheckoutPage {...props} />;
                break;
            //other switch cases...
            default:
                //should I return my 404 component here?
                component = <DefaultPage {...props} />;
        }
        return component;
    };

    return getPages();
};

export async function getServerSideProps(context) {
    const res = await getReq(`/getUrl`, 'content', context);

    switch (res.url) {
        case 'checkout': {
            return {
                props: {
                    url: res.url,
                    props: {
                    ... //my other props
                    },
                },
            };
        }
        default:
            return {
                props: null,
            };
    }
}

Pid.propTypes = {
    url: PropTypes.string.isRequired,
};

export default Pid;

从 NextJS 10 开始,由于新标志notFound: true ,您不必显式返回 404 页面。 您可以在getStaticPropsgetServerSideProps中使用它来自动触发默认 404 页面或您自己的自定义 404 页面。

从 NextJS 文档中查看这些示例。

export async function getStaticProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: { data }, // will be passed to the page component as props
  }
}
export async function getServerSideProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: {}, // will be passed to the page component as props
  }
}

文档参考

  1. Nextjs10 上的 notfound 支持

  2. 在 getStaticProps 上找不到

  3. 在 getserversideprops 上找不到

  4. 自定义 404 页面

从 Next.js 10 开始,您可以从getServerSideProps返回notFound: true以触发 404 页面。

export async function getServerSideProps(context) {
    const res = await getReq(`/getUrl`, 'content', context);
    switch (res.url) {
        case 'checkout': {
            return {
                props: {
                    //my other props
                },
            };
        }
        default:
            return {
                notFound: true
            };
    }
}

作为示例,我已将它放在default情况下,但您可以在任何其他点/条件下随意返回它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM