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

yra*_*lik 13 javascript next.js

[pid].js我的 Next.js 项目中有一个文件。我还想实现自定义 404 页面,但问题是:我将404.js文件放在/pages目录中。如果我删除我的[pid].js文件,404 页面就可以正常工作。但是,如果我保留我的[pid].js文件,第一个请求将进入 pids,并且由于 url 与 pids 中定义的任何页面都不匹配,我会收到错误。我应该从 pid 显式返回我的 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;
Run Code Online (Sandbox Code Playgroud)

kes*_*lal 26

从 NextJS 10 开始,由于有了新标志,您不必显式返回 404 页面notFound: true。您可以使用它来getStaticProps自动getServerSideProps触发默认 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
  }
}
Run Code Online (Sandbox Code Playgroud)
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
  }
}
Run Code Online (Sandbox Code Playgroud)

文档参考

  1. notfound 对 Nextjs10 的支持

  2. 在 getStaticProps 上未找到

  3. 在 getserversideprops 上找不到

  4. 自定义 404 页面


jul*_*ves 10

从 Next.js 10 开始,您可以notFound: truegetServerSideProps触发 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
            };
    }
}
Run Code Online (Sandbox Code Playgroud)

我已将其放入default箱子中作为示例,但请随时在任何其他时间/条件下将其退回。