i have dynamic route of products
import React from 'react';
import { useSelector } from 'react-redux';
import { Container, Row, Col } from 'reactstrap';
const Product = (props) => {
const products = useSelector(state => state.products);
const product = products.find(product => product.title === props.match.params.title);
const {
title,
image,
description
} = product;
return (
<div className="product">
<Container>
<Row className="d-flex justify-content-center">
<Col lg="8">
<img width="100%" src={image} alt={title} />
</Col>
</Row>
<Row className="mt-5 d-flex justify-content-center">
<Col lg="8">
<p>{description}</p>
</Col>
</Row>
</Container>
</div>
)
}
export default Product;
but how to handle when product not find and product is undefined and cannot read property title, image, description of undefined
There are different strategies to handle this.
If you want to show a fallback product:
product
to get rid of the error messageproduct
const {
title = 'title',
image = 'fallback.jpg',
description = 'this is the description'
} = product || {};
If you want to display a message, that no product was found:
product
is undefined
or null
before destructuring itif(!product) {
return <p>no product found</p>
}
const { title, image, description } = product;
Do the following
const Product = props => {
const products = useSelector(state => state.products);
const product = products.find(product => product.title === props.match.params.title);
const { title, image, description } = product ? product :{};
return (
<div className="product">
{
product ?
<Container>
<Row className="d-flex justify-content-center">
<Col lg="8">
<img width="100%" src={image} alt={title} />
</Col>
</Row>
<Row className="mt-5 d-flex justify-content-center">
<Col lg="8">
<p>{description}</p>
</Col>
</Row>
</Container>
: <div>Not Found</div>
}
</div>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.