簡體   English   中英

NextJS - 在 1 頁上進行多次提取的動態路由

[英]NextJS - Dynamic Routing with multiple fetch on 1 Page

我正在嘗試使用 NextJS 重建我的 CRA 網站,但我有點卡在這個頁面上

中間容器有 3 個部分:

  • 字母列表(沒問題)
  • 索引列表(僅 1 次獲取以獲取列表)
  • 所選索引的描述(每次用戶在列表中選擇一個新索引時都會更改)

它與 CRA 完美配合。 所以,用NextJS,我做了以下內容:指標的列表中有,每個索引項,鏈接組件,例如: "https://www.phidbac.fr/Liste-des-index/50"

和 pages/Liste-des-index 文件夾中的文件[id].js

// 獲取每個新選擇的列表和描述

const Indexes = ({ listeIndex, cours, id }) => {
  return (
    <>      
      <Layout>
        <PageIndex listeIndex={listeIndex} id={id} cours={cours} />
      </Layout>
    </>
  );
};

export default Indexes;

Indexes.getInitialProps = async ({ req }) => {

// Get the correct ID Description from URL
  let id = req.url;
  id = id.split("/")[2];

  const res = await fetch("https://www.phidbac.fr:4000/Indexes");
  const dataList = await res.json();
  const res1 = await fetch(`https://www.phidbac.fr:4000/Indexes/${id}`);
  const dataDescription = await res1.json();

  return {
    listeIndex: dataList,
    cours: dataDescription,
    id: id
  };
};

它正在工作,但此頁面在每次點擊時都會完全重新加載,因此速度很慢,顯然不是一個好的解決方案。

Github 存儲庫

我怎樣才能實現像 CRA 版本一樣流暢的東西?

感謝您的幫助:D

編輯 :

在此屏幕截圖中,您可以看到單擊和頁面加載之間的延遲,以及滾動容器返回到開頭。

例子

我只是盡量不要在每次點擊時刷新索引列表,而只是從右側更改描述。

如果您想嘗試,我已經用您的解決方案編輯了 git。

再次感謝 :)

您用於[id-name].js頁面的命名約定是 Next.js 的動態路由功能的一部分。 通過稍微修改您的代碼,將next/link用於 Dynamic routes ,我想我設法實現了您的要求。

在此處輸入圖片說明

首先,您必須修改ListeIndex.tsx並使用來自next/link Link組件與 props hrefas (更多關於上面提供的鏈接和下面的評論)

// ListeIndex.tsx

import Link from 'next/link'
// const { Link } = routes;

...

<Link
  key={element.id}
  prefetch={false}
  href="/Liste-des-index/[id-name]" // `href` points to page [id-name].js
  as={`/Liste-des-index/${element.id}-${element.nom // `as` holds the data you need to pass
    .replace(/\u202f/g, "-") 
    .replace(/\//g, "-")}`}> 

...

然后,你只需要修改你的[id-name].tsx ,並期望你的數據被query而不是req

// [id-name].tsx

...

Indexes.getInitialProps = async ({ query }: any) => {
  const id = query['id-name'].split("-")[0]; // you should find your data under `query` parameter

...

暫無
暫無

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

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