简体   繁体   English

我该如何解决这个问题 我尝试搜索匹配路线,但没有显示任何内容?

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

this my single product page这是我的单品页面

    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';* 

This where I tired to find the match id and render the product with match id这是我厌倦了找到匹配 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;

This is my single product screen这是我的单品界面

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;

Try this:尝试这个:

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

Your product page:您的产品页面:

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
},[]);  

Issue问题

In react-router-dom v6 the Route components no longer have route props ( history , location , and match ), and the current solution is to use the React hooks "versions" of these to use within the components being rendered.在 react-router-dom v6 中, Route组件不再有路由属性( historylocationmatch ),当前的解决方案是使用这些组件的 React hooks“版本”在被渲染的组件中使用。

In other words, props.match is undefined.换句话说, props.match是未定义的。 This should also be clear since no props are passed to Products .这也应该很清楚,因为没有道具传递给Products

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

Solution解决方案

Use the useParams hook to access the id route path param in the Products component.使用useParams挂钩访问Products组件中的id路由路径参数。 Don't forget that Array.prototype.find can potentially return undefined if no element matches the predicate, so your UI code should handle this case.不要忘记,如果没有元素与谓词匹配, Array.prototype.find可能会返回 undefined,因此您的 UI 代码应该处理这种情况。 ( avoids "undefined access of X" exceptions ) 避免“未定义的 X 访问”异常

Example:例子:

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.

相关问题 Layout 无法显示任何内容,我想知道如何解决使用 Route with Layout 的问题? - Can't show any thing with Layout, I want to know How to fix this problem that using Route with Layout? 我该如何解决这个问题 - 我尝试了所有方法但不起作用 - How can I fix this - I tried everything but doesn't work ReactNative State 不会立即改变,所以我该如何解决我的问题? - ReactNative State doesn't change immediately so how can I do to fix my problem? 材质 UI 元素不会显示。 一个棕褐色框显示而不是任何 MUI 元素。 我怎样才能解决这个问题? - Material UI Elements won't show. A tan box shows instead of any MUI element. How can I fix this? 如果密码与数据库中的密码不匹配,如何显示? - How can I display if the password doesn't match the one in the database? 谁能明白为什么我会收到“无效的钩子”错误? 我试了又试,看不出问题出在哪里 - Can anyone see why I'm getting an "invalid hook" error? I have tried and tried and can't see what the problem is 我该如何解决这个下拉菜单显示问题? - How can i fix this dropmenu display problem? 如何解决ReactJS中的字符集问题? - How can I fix charset problem in ReactJS? 如何从页面中删除数据并且它不显示? - How can I remove data from the page and it doesn't show? 我对 npx create react app 有一些问题可以请教我如何修复它 - i ve some problem with npx create react app can sbd show me how to fix it plss
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM