javascript - NextJS - 在一页上进行多次获取的动态路由

标签 javascript reactjs routes fetch next.js

我正在尝试使用 NextJS 重建我的 CRA 网站,但我有点卡住了 page :

中间容器有 3 个部分:

  • 信件列表(没问题)
  • 索引列表(仅获取 1 次即可获取列表)
  • 所选索引的描述(每次用户在列表中选择新索引时,此描述都会发生变化)

它与 CRA 完美配合。 因此,使用 NextJS,我执行了以下操作: 对于每个索引项,索引列表都有一个链接组件,例如: “https://www.phidac.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 Repository

如何实现像 CRA 版本一样流畅的效果?

感谢您的帮助:D

编辑:

在此屏幕截图中,您可以看到单击和页面加载之间的延迟,以及滚动容器返回到开头的情况。

Example

我只是尝试不在每次点击时刷新索引列表,而只是更改右侧的描述。

如果你想尝试的话,我已经用你的解决方案编辑了 git。

再次感谢:)

最佳答案

您为 [id-name].js 页面使用的命名约定是 Dynamic routes 的一部分。 Next.js 的功能。通过稍微修改您的代码,使用 next/link for Dynamic routes ,我想我已经达到了你的要求。

enter image description here

首先,您必须修改 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

...

关于javascript - NextJS - 在一页上进行多次获取的动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024719/

相关文章:

javascript - 给已有参数的函数 prop 添加参数

javascript - ReactJs 如何呈现关联数组的对值

javascript - event.target.name 未定义

Laravel 5 资源丰富的路由和中间件

laravel - 使用 Laravel 路由在 url 中显示名称而不是 id

javascript - 转换div时如何阻止 sibling 移动?

javascript - 监听 HTML 元素,无需 setInterval

javascript - 检查是否包含 jQuery

javascript - 导出模块包

Azure 应用程序网关将 "/*"转发到后端池