reactjs - 使用 next.js 中的钩子以编程方式进行动态导航
问题描述
我有一个基于 next.js 框架的应用程序,其中我使用材料表组件来处理项目中的表。这个库有一个名为 onRowClick 的 props,它反过来接受一个附加到列中每一行的原生 onClick 道具的函数。我现在想要得到的是一个动态链接,它将把用户带到点击时的适当页面。
在 next.js 中动态链接对我来说仍然有点不清楚,但到目前为止我已经尝试过:
//The class organizin paths in the application (simplified)
export default class Routes {
public static PLAYERS = '/players';
public static PLAYER = (id: number) => `${Routes.PLAYERS}/${id}`;
public static PLAYER_SCHEME = `${Routes.PLAYERS}/[id]`;}
….
const router = useRouter();
//I am providing here a dynamic path scheme and as the second dynamic path parameter to be filled for each player separately
const redirect = async (id: number) => router.push(Routes.PLAYER_SCHEME, Routes.PLAYER(id));
…
//Passing function to the table
onRowClick={async (_, row) => (row?.id ? redirect(row.id) : undefined)}
一切都可能运作良好。但是,我Players
在 Pages 文件夹中的组件正在根据来自 url 的 id 参数执行对 api 数据的请求。不幸的是,以这种方式将路由推送到路由器,两次渲染pages/Players/[id]
组件,第一次在 params id 中得到一个 null 和下一个正确的 id。
TL;DR 当我无法使用 Link 组件时,在 next.js 中创建动态链接的正确方法是什么,因为它会破坏 app html 结构的语义。
解决方案
您可以使用 Next.js 中的路由器
import Router from 'next/router'
cosnt redirect = (url) => {
Router.push(url)
}
例如:
Router.push('/login');
Router.push('/products/' + id);
推荐阅读
- php - 在 PhpStorm 版本 2019.2.4 中,类名出现错误
- html - Bootstrap,如何使容器流体的高度为 100%
- ios - 如何在 Xcode 中创建动态包标识符
- audio - 如何从 iPhone 11 或 iPhone 11 Pro Max 获取采样率为 44100 的音频
- promise - vertx中的future和promise有什么区别?
- r - R中的两阶段聚类抽样
- google-apps-script - 谷歌表格宏不会复制/粘贴正确的随机生成的值
- angular - 我们可以在 SVG 模板中渲染 Angular 组件吗?
- api - Cloudflare api v4 更改了其协议
- laravel - 如何从 Laravue 中的其他文件请求响应中获取响应