react怎么獲取路由參數(shù)

小億
549
2024-01-25 17:02:31

React可以使用react-router庫(kù)來(lái)獲取路由參數(shù)。下面是使用react-router獲取路由參數(shù)的步驟:

  1. 首先,確保已經(jīng)安裝了react-router-dom庫(kù)。可以使用以下命令進(jìn)行安裝:
npm install react-router-dom
  1. 在應(yīng)用程序的根組件中,引入BrowserRouterRoute組件,并設(shè)置路由規(guī)則。例如:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import Home from './Home';
import Product from './Product';

const App = () => {
  return (
    <Router>
      <Route exact path="/" component={Home} />
      <Route path="/product/:id" component={Product} />
    </Router>
  );
}

export default App;
  1. 在目標(biāo)組件中,可以通過(guò)props對(duì)象的match.params屬性來(lái)獲取路由參數(shù)。例如,在Product組件中獲取id參數(shù):
import React from 'react';

const Product = (props) => {
  const { id } = props.match.params;

  return <h1>Product ID: {id}</h1>;
}

export default Product;

在上面的例子中,當(dāng)訪問(wèn)/product/123時(shí),Product組件會(huì)被渲染,并且id參數(shù)的值為123。

0