# 获取路由参数

react-router-dom V6 版本

import React from "react";
import {useParams, useSearchParams} from 'react-router-dom';

export const DetailPage: React.FC = () => {
  const [search] = useSearchParams();
  const params = useParams<{label: string; [key: string]: string}>()

  return (
    <>
      <h1>label:{params.label}</h1>
      <h1>tag:{params['*']}</h1>
      <h1>sort:{search.get('sort')}</h1>
    </>
  )
}

路由配置

import React from 'react';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
import styles from './App.module.css';
import {DetailPage} from "./pages";

function App() {
  return (
    <div className={styles.App}>
      <BrowserRouter>
        <Routes>
          <Route path={'/detail/:label/*'} element={<DetailPage/>}/>
        </Routes>
      </BrowserRouter>
    </div>
  );
}
export default App;

参考文章:

react-router-dom v6 实现可选参数传递以及获取 (opens new window)

更新时间: 2022年9月29日星期四下午2点53分