簡體   English   中英

我該如何解決這個問題 我嘗試搜索匹配路線,但沒有顯示任何內容?

[英]how can I fix this problem I tried search for the match route but it doesn't show any thing?

這是我的單品頁面

    import React from "react";
    import { Link } from "react-router-dom";
    import Rating from "../components/Rating";
    import Product from "../Data";
    import { Row, Button, Col, Image, ListGroup, Card } from "react-bootstrap";
    // import PropTypes from 'prop-types';* 

這是我厭倦了找到匹配 ID 並使用匹配 ID 呈現產品的地方

    const Products = ({match}) => {
      const product = Product.find((p) => p._id === match.params.id);
      return (
        <>
          <Link className="btn btn-dark my-3" to="/" />
          Go Back
          <Row>
            <Col md={6}>
              <Image src={product.img} fluid />
            </Col>
            <Col md={3}>
              <ListGroup variant="flush">
                <ListGroup.Item>
                  <h3>{product.name}</h3>
                </ListGroup.Item>
              </ListGroup>
              <ListGroup.Item>
                <Rating
                  value={product.Rating}
                  text={`${product.numReviews}`}
                />
              </ListGroup.Item>
              <ListGroup.Item>
                <p>Description:{product.desc}</p>
              </ListGroup.Item>
              <ListGroup.Item>
                <p>price: $ {product.price}</p>
              </ListGroup.Item>
            </Col>
            <Col md={3}>
              <Card>
                <ListGroup variant="flush">
                  <ListGroup.Item>
                    <Row>
                      <Col>Price:</Col>
                      <Col>
                        <strong>$ {product.price}</strong>
                      </Col>
                    </Row>
                  </ListGroup.Item>
                  <ListGroup.Item>
                    <Row>
                      <Col>Status:</Col>
                      <Col>
                        {product.countInStock > 0 ? "In Stock" : "Out Of Stock"}
                      </Col>
                    </Row>
                  </ListGroup.Item>
                  <ListGroup.Item>
                    <Button
                      className="btn btn-primary"
                      type="button"
                      disabled={product.countInStock === 0}
                    >
                      Add To Cart
                    </Button>
                  </ListGroup.Item>
                </ListGroup>
              </Card>
            </Col>
          </Row>
        </>
      );
    };

    

export default Products;

這是我的單品界面

import Products from "./pages/Products";
const App = () => {
  return (
    <BrowserRouter>
      <Header />
      <main className="py-3">
        <Container>
          <Routes>
            <Route  index element={<Home />} />
            <Route path="product" element={<Products />} />
            <Route path=":id" element={<Products />} />

          </Routes>
        </Container>        
      </main>
      <Footer />
    </BrowserRouter>
  );
};

export default App;

嘗試這個:

<Routes>
    <Route path="/" element={<Home />} />
    <Route path="product/:id" element={<Products />} />
</Routes>

您的產品頁面:

const {id} = useParam() // we can destructure out the id

const fetchProduct = async (id) => {
    const resultFromServer = await fetch(`url/${id}`)
    const dataFromServer = await resultFromServer.json()
    // with the data, now we can store it in useState or Context api
    // depends on your implementation, and show it to the client
}

useEffect(() => {
    if(id) fetchProduct(id) // Fetch product based on url id
},[]);  

問題

在 react-router-dom v6 中, Route組件不再有路由屬性( historylocationmatch ),當前的解決方案是使用這些組件的 React hooks“版本”在被渲染的組件中使用。

換句話說, props.match是未定義的。 這也應該很清楚,因為沒有道具傳遞給Products

<Route path=":id" element={<Products />} /> // <-- no props passed to Products

解決方案

使用useParams掛鈎訪問Products組件中的id路由路徑參數。 不要忘記,如果沒有元素與謂詞匹配, Array.prototype.find可能會返回 undefined,因此您的 UI 代碼應該處理這種情況。 避免“未定義的 X 訪問”異常

例子:

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

const Products = () => {
  const { id } = useParams();

  const product = Product.find((p) => p._id === id);

  if (!product) return "No matching product found.";

  return (
    <>
      ...
    </>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM