繁体   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