簡體   English   中英

在反應中找不到產品時處理

[英]handle when product not found in react

我有產品的動態路線

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;

但是當產品未找到且產品未定義且無法讀取屬性標題、圖像、未定義描述時如何處理

有不同的策略來處理這個問題。

如果要顯示后備產品:

  • 使用一個空的 object 作為product的后備來擺脫錯誤消息
  • product的屬性分配默認值
const {
    title = 'title',
    image = 'fallback.jpg',
    description = 'this is the description'
} = product || {};

如果您想顯示一條消息,即未找到產品:

  • 在解構之前檢查product是否undefinednull
  • 如果是這種情況,則返回自定義消息
if(!product) {
    return <p>no product found</p>
}

const { title, image, description } = product;

請執行下列操作

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>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM