简体   繁体   English

带有用户输入 URL 的 Next.js 动态路由

[英]Next.js Dynamic Route With a User Inputted URL

I am using the Next.js Router to enable different dashboards depending on the URL slug.我正在使用 Next.js 路由器根据 URL slug 启用不同的仪表板。 This works when a button with the link is clicked, as the link passes the information to the Next.js Router, but it does not work when a URL is inputted directly into the browser (ie it does not work if the user refreshes the page, or just types the URL with the slug directly).这在带有链接的按钮被点击时起作用,因为链接将信息传递给 Next.js 路由器,但是当 URL 直接输入浏览器时不起作用(即,如果用户刷新页面则不起作用,或者直接输入带有 slug 的 URL)。 So, while I am able to use dynamic routes when links are pressed, how can I enable dynamic routes when a link is not pressed?因此,虽然我可以在按下链接时使用动态路由,但如何在未按下链接时启用动态路由?

The relevant code is below.相关代码如下。 Thank you very much非常感谢

const dashboard = () => {
  const router = useRouter();
  const {dashboardID} = router.query;

  return (
    <Dashboard dashboardID = {dashboardID}/>
  );
}

export default dashboard

On pagination the query already loaded on the context.在分页时,查询已经加载到上下文中。

You need to wait until router fully loads您需要等到路由器完全加载

const dashboard = () => {
      const router = useRouter();
      const {dashboardID} = router.query;
      
      if(!dashboardID) return null //Wait until query with dashboardID loads to avoid undefined errors 
      return (
        <Dashboard dashboardID = {dashboardID}/>
      );
    }
    
    export default dashboard

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

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