简体   繁体   中英

useParam is not working in react router Dom v6?

I am trying to pass a parameter to my other component which is productDetail component but when I am trying to access that parameter value using useParam it doesn't seems to work:

App:

import React from "react";
import { Route, Routes } from "react-router-dom";
import MainHeader from "./components/MainHeader.jsx";
import Product from "./pages/Product.jsx";
import ProductDetails from "./pages/ProductDetails.jsx";
import Welcome from "./pages/Welcome.jsx";

const App = () => {
  return (
    <div style={{ textAlign: "center" }}>
      <header>
        <MainHeader />
      </header>
      <Routes>
        <Route path="/welcome" element={<Welcome />} />
        <Route path="/product" element={<Product />} />
        <Route path="/products/:productId" element={<ProductDetails />} />
      </Routes>
    </div>
  );
};

export default App;

ProductDetailes:

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

const ProductDetails = () => {
  const params = useParams;
  console.log(params.productId);

  return (
    <div>
      <h1>Product Detail</h1>
      <p>{params.productId}</p>
    </div>
  );
};

export default ProductDetails;

The useParams hook is a function and actually needs to be invoked in order to have any effect.

Example:

const ProductDetails = () => {
  const { productId } = useParams();

  useEffect(() => {
    console.log({ productId });
  }, [productId]);

  return (
    <div>
      <h1>Product Detail</h1>
      <p>{productId}</p>
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM