乐闻世界logo
搜索文章和话题

Difference between router.pathname and router.route in nextjs

1个答案

1

In Next.js, both router.pathname and router.route are concepts associated with the routing system, but they refer to slightly different aspects.

router.pathname

router.pathname represents the path displayed in the browser's address bar. It is dynamic and updates as you navigate through the application. For example, if you visit the /about page, router.pathname will be /about.

Example: If your page structure is designed as /posts/[id], when a user visits /posts/123, router.pathname will be /posts/123.

router.route

In contrast, router.route represents the actual path template of the page, rather than the specific dynamic path. It serves as an internal representation of the page structure within Next.js projects.

Example: Continuing with the /posts/[id] example, regardless of the actual id value (e.g., /posts/123 or /posts/456), router.route remains /posts/[id], indicating that it is a dynamic route where [id] is a placeholder.

Core Differences

  • Dynamic Nature:

    • router.pathname is dynamic and changes as the actual path changes.
    • router.route is fixed and represents the route template.
  • Purpose:

    • router.pathname can be used to display the current path or dynamically show the current location in breadcrumb navigation.
    • router.route is typically used in route guards or logic that requires operations based on the route template, such as dynamically loading components or data.

Application Scenario Example

Suppose you are developing a blog system where you need to dynamically display article content based on the article ID, while also highlighting the currently selected category in the navigation bar.

  • Use router.pathname to implement the highlighting logic for the navigation bar, as you need to determine the specific article the user is currently visiting based on the full path.
  • Use router.route to determine whether to load the article content, as the route template remains /posts/[id] regardless of the article ID, allowing you to load the corresponding article data based on this fixed template.

Through this approach, you can effectively utilize Next.js's routing system to build a flexible and efficient application.

2024年7月18日 01:03 回复

你的答案