简体   繁体   中英

handle when product not found in react

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:

  • Use an empty object as fallback for product to get rid of the error message
  • Assign default values to the properties of product
const {
    title = 'title',
    image = 'fallback.jpg',
    description = 'this is the description'
} = product || {};

If you want to display a message, that no product was found:

  • Check if product is undefined or null before destructuring it
  • Return a custom message if this is the case
if(!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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM