React 使用 Router 获取当前路由

使用 useLocation() 钩子通过 React Router 获取当前路由,例如 const location = useLocation() 。 钩子返回当前位置对象。 例如,我们可以将路径名作为 location.pathname 访问。

import React from 'react';
import {Route, Link, Routes, useLocation} from 'react-router-dom';

export default function App() {
  const location = useLocation();

  console.log('hash', location.hash);
  console.log('pathname', location.pathname);
  console.log('search', location.search);

  return (
    
      
        

Current Pathname ️ {location.pathname}

Current Search params ️ {location.search}

Current Hash ️ {location.hash}

} /> } /> ); } function Home() { return

Home

; } function About() { return

About

; }

我们使用 useLocation 钩子来获取当前位置的对象。

可以在位置对象上访问的一些属性是:

  • pathname - 当前路径名,例如 /用户
  • search - 当前查询的字符串,例如 ?page=10
  • hash - 当前的哈希值,例如 #example

使用 react 路由器钩子时,请确保将我们的应用程序封装在 index.js 文件中的路由器组件中。

import {createRoot} from 'react-dom/client';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

// wrap App in Router
root.render(
  
    
  
);

用 Router 组件包装 React 应用程序的最佳位置是在 index.js 文件中,因为这是 React 应用程序的入口点。

一旦你的整个应用被一个 Router 组件包裹,你就可以在组件的任何地方使用来自 react router 包的任何钩子。

如果有动态路由并尝试访问其 ID,请使用 useParams 钩子。

import React from 'react';
import {Route, Link, Routes, useParams} from 'react-router-dom';

function Users() {
  // get ID from url
  const params = useParams();

  console.log(params); // {userId: '12345'}

  return 

userId is ️ {params.userId}

; } export default function App() { return ( } /> {/* handle dynamic path */} } /> } /> ); } function Home() { return

Home

; } function About() { return

About

; }

useParams 钩子从当前 URL 返回与 匹配的动态参数的键值对对象。

请注意,我们在渲染用户组件的 Route 组件上设置了一个动态路径属性 - } />

当访问 /users/some-id 时,我们可以使用 useParams 钩子来获取 ID。

function Users() {
  // get ID from url
  const params = useParams();

  console.log(params); // ️ {userId: '12345'}

  return 

userId is ️ {params.userId}

; }

该路由将匹配 /users/ 之后的任何内容,例如 /users/123/users/asdf

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章