问题
So I'm creating a e-commerce store for a sideproject, but I'm stuck on a problem. On the main page I have all the products, and I've created a route for the product details. When I click on one of them, it gets the id, and should output all the product details. I have the details about products in a JSON array "data.js".
When I click on a product in the main page, it displays the error: TypeError: Cannot read property 'image' of undefined
- in the return
part, where I put {product.image}
in.
However, when I uncomment the part where it checks whether product exists or not (ProductPage.js), it still outputs "Item does not exist!"
, as if there weren't any data about the product in "data.js" file.
App.js
<Route path="/product/:id" component={ProductPage}></Route>
ProductPage.js
import React from 'react';
import data from '../data';
export default function ProductPage(props) {
const product = data.products.find((x) => x._id === props.match.params.id);
// if (!product) {
// return <div>Item does not exist!</div>
// }
return (
<div>
<div className="row">
<div className="col">
<img src={product.image} alt={product.name}></img>
</div>
</div>
</div>
);
}
Data.js
const data = {
products:[
{
_id: 1,
name: 'iPhone 11 Pro',
category: 'Smartphones',
image: '/images/2.jpg',
price: 949,
rating: 4.8,
numReviews: 15,
description: 'testtesttesttesttesttesttesttest',
},
],
};
export default data;
Thanks in advance.
回答1:
You need to wrap your ProductPage component with withRouter to access props.match.params.id.
Edit: if you are going to use props.match.params.id for comparison, keep in mind that it is a string
Change your ProductPage component to:
import React from 'react';
import data from '../data';
import {withRouter} from 'react-router';
function ProductPage(props) {
const product = data.products.find((x) => x._id === props.match.params.id);
return (
<div>
<div className="row">
<div className="col">
<img src={product.image} alt={product.name}></img>
</div>
</div>
</div>
);
}
export default withRouter(ProductPage);
来源:https://stackoverflow.com/questions/64727803/react-typeerror-cannot-read-property-image-of-undefined