簡體   English   中英

如何避免 Next.js 動態路由中的“id undefined”?

[英]How to avoid "id undefined" in Next.js dynamic route?

我正在使用路由器從一頁轉到另一頁:

    const goToArticle = (index) => {
      router.push({
        pathname: `/article/${index}`,
      })
    }

我要去的頁面被命名為[id].js並導出為Article

在文章頁面中,我試圖獲取該索引:

export async function getStaticPaths({id})  {
  const res = await fetch('myurl');
  const articles = await res.json();
  console.log(params.id);
  return {
      props: {
          article: articles.items[id]
      }
      }
}

錯誤:ID 未定義

類型錯誤:無法解構“未定義”的屬性“id”,因為它未定義。

如何獲取該索引並返回具有該索引的數組項?

您可以更改函數重定向如下:

const goToArticle = (index) => {
  router.push({
    pathname: `/article/[id]`,
    as: `/article/${index}`,
  })
}

請參考文檔: https : //nextjs.org/docs/api-reference/next/router

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM