本文共 1742 字,大约阅读时间需要 5 分钟。
next.js 多级路由
In we saw how to use the Link component to declaratively handle routing in Next.js apps.
我们看到了如何使用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 insidecomponendDidMount()
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 .
您也可以使用路由器侦听 。
翻译自:
next.js 多级路由
转载地址:http://gxqgb.baihongyu.com/