如何解决此问题,我尝试搜索匹配路由,但它没有显示任何内容?



这是我的单一产品页面

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;

问题

在react路由器dom v6中,Route组件不再具有路由道具(historylocationmatch(,并且当前的解决方案是使用react钩子";版本";在正在渲染的组件中使用。

换句话说,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 (
<>
...
</>
);
};

试试这个:

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

相关内容