参数不能从反应路由传递到反应组件

Parameter can not be passed from react route to react Component

我已经尝试过之前的解决方案,但 react-dom 的 v6 似乎无法正常工作。

我无法将 id 从路径传递到组件。

app.js

import Container from 'react-bootstrap/Container'
import Footer from './components/Footer';
import Header from './components/Header';
import './index.css';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';

function App() {
  return (
    <Router>
      <Header/>
      <main className='py-3'>
        <Container >
         <Routes>
           <Route path="/" exact element={<HomeScreen/>} />
           
            {/* Please check this. I am passing id as a param */}
           <Route path="/product/:id"  element={<ProductScreen/>} />
         </Routes>
        </Container>
      </main>
      <Footer/>
    </Router>
  );
}

export default App;

问题在

<Route path="/product/:id"  element={<ProductScreen/>} />

我正在将 :id 传递给 ProductScreen 组件。

ProductScreen.js

import React from 'react'
import {Link} from 'react-router-dom'
import {Row, Col, Image, ListGroup, Button, Card} from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'

function ProductScreen({match}) {
  const product = products.find((p)=>p._id==match.params.id)
  return (
    <div>
      {product.name}
    </div>
  )
}

export default ProductScreen

我无法从路径访问产品 ID。

错误:

您需要获取 useParams 挂钩才能使用参数。 https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params

你可以这样做:

import React from 'react'
import {Link, useParams} from 'react-router-dom'
import {Row, Col, Image, ListGroup, Button, Card} from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'

function ProductScreen({match}) {
  const params = useParams()
  const product = products.find((p)=>p._id==params.id)
  return (
    <div>
      {product.name}
    </div>
  )
}

export default ProductScreen

你可能想像这样简化它。

import React from 'react'
import {useParams} from 'react-router-dom'
import {Row, Col, Image, ListGroup, Button, Card} from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'

function ProductScreen() {

  const {id} = useParams()

  const product = products.find((p)=>p._id===id)
  return (
    <div>
      {product.name}
    </div>
  )
}

export default ProductScreen