next.js 多级路由_如何使用Next.js路由器

next.js 多级路由

In linking two pages in Next.js using Link we saw how to use the Link component to declaratively handle routing in Next.js apps.

使用Link在Next.js中链接两个页面时,我们看到了如何使用Link组件以声明方式处理Next.js应用程序中的路由。

It’s really handy to manage routing in JSX, but sometimes you need to trigger a routing change programatically.

在JSX中管理路由确实很方便,但是有时您需要以编程方式触发路由更改。

In this case, you can access the Next.js Router directly, provided in the next/router package, and call its push() method.

在这种情况下,您可以直接访问next/router软件包中提供的Next.js路由器,并调用其push()方法。

Here’s an example of accessing the router:

这是访问路由器的示例:

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()
  //...
}

Once we get the router object by invoking useRouter(), we can use its methods.

通过调用useRouter()获得路由器对象后,就可以使用其方法了。

This is the client side router, so methods should only be used in frontend facing code. The easiest way to ensure this is to wrap calls in the useEffect() React hook, or inside componendDidMount() in React stateful components.

这是客户端路由器,因此方法仅应在面向前端的代码中使用。 确保这一点的最简单方法是将调用包装在React的useEffect() ,或包装在React有状态组件的componendDidMount()中。

The ones you’ll likely use the most are push() and prefetch().

您可能最常使用的是push()prefetch()

push() allows us to programmatically trigger a URL change, in the frontend:

push()允许我们在前端以编程方式触发URL更改:

router.push('/login')

prefetch() allows us to programmatically prefetch a URL, useful when we don’t have a Link tag which automatically handles prefetching for us:

prefetch()允许我们以编程方式预取URL,这在我们没有可自动为我们处理预取的Link标记时非常有用:

router.prefetch('/login')

Full example:

完整示例:

import { useRouter } from 'next/router'

export default () => {
  const router = useRouter()

  useEffect(() => {
    router.prefetch('/login')
  })
}

You can also use the router to listen for route change events.

您也可以使用路由器侦听路由更改事件

翻译自: https://flaviocopes.com/nextjs-router/

next.js 多级路由

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值