我正在尝试使用 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
};
};
它正在工作,但此页面在每次点击时都会完全重新加载,因此速度很慢,显然不是一个好的解决方案。
如何实现像 CRA 版本一样流畅的效果?
感谢您的帮助:D
编辑:
在此屏幕截图中,您可以看到单击和页面加载之间的延迟,以及滚动容器返回到开头的情况。
我只是尝试不在每次点击时刷新索引列表,而只是更改右侧的描述。
如果你想尝试的话,我已经用你的解决方案编辑了 git。
再次感谢:)
最佳答案
您为 [id-name].js
页面使用的命名约定是 Dynamic routes 的一部分。 Next.js 的功能。通过稍微修改您的代码,使用 next/link
for Dynamic routes ,我想我已经达到了你的要求。
首先,您必须修改 ListeIndex.tsx
并使用 next/link
中的 Link
组件以及 props href
和 as
(有关更多信息,请参见上面提供的链接和下面的评论)
// 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/