开发者问题收集

未捕获的类型错误:无法读取未定义的属性(读取“图像”)

2022-06-16
2379

我使用 const { id } = useParams(); 修复了“Uncaught TypeError: Cannot read properties of undefined (reading 'params')”之后立即出现此错误。

ProductDetail.jsx

import React, { Fragment, useEffect } from 'react';
import Carousel from "react-material-ui-carousel";
import "./ProductDetails.css";
import {useSelector, useDispatch} from "react-redux";
import { getProductDetails } from '../../actions/productAction';
import { useParams } from 'react-router-dom';


const ProductDetails = ({}) => {
  const { id } = useParams();
  const dispatch = useDispatch();

  const { product, loading, error } = useSelector(
    (state) => state.productDetails
  );

  useEffect(() => {
    dispatch(getProductDetails(id));
  }, [dispatch, id]);

  return (
    <Fragment>
      <div className="ProductDetails">
        <div>
          <Carousel>
            {product.images && product.images.map((item, i) => (
              <img
                className='CarouselImage'
                key={item.url}
                src={item.url}
                alt={`${i} Slide`} 
              />
            ))}
          </Carousel>
        </div>
      </div>
    </Fragment>
  );
};

export default ProductDetails

控制台错误:抱歉,这是一张图片,不知道如何发布

enter image description here

2个回答
product.images && product.images.map((item, i) =>(

此行产品可能未定义。如果产品可能存在或可能不存在,请使用 product?.images?.map

Kalpesh
2022-06-16

此错误通知您 product 变量未定义。

使用 null-check/guard 子句保护它

product && product.images && product.images.map(.....

或使用可选链式运算符

product?.images?.map(.....

由于此 ProductDetails 组件似乎在组件安装后获取 product 数据,因此您需要防止 product 在初始渲染和任何后续渲染中未定义,直到 productDetails 状态被填充。在这里,当 product 未定义时,有条件地渲染 null 或某些加载指示器可能更好。

示例:

const ProductDetails = () => {
  const { id } = useParams();
  const dispatch = useDispatch();

  const { product, loading, error } = useSelector(
    (state) => state.productDetails
  );

  useEffect(() => {
    dispatch(getProductDetails(id));
  }, [dispatch, id]);

  return (
    <Fragment>
      <div className="ProductDetails">
        <div>
          {product?.images
            ? (
              <Carousel>
                {product.images?.map((item, i) => (
                  <img
                    className='CarouselImage'
                    key={item.url}
                    src={item.url}
                    alt={`${i} Slide`} 
                  />
                ))}
              </Carousel>
            )
            : (
              <div>Fetching Product Details</div>
            )
          }
        </div>
      </div>
    </Fragment>
  );
};

export default ProductDetails;
Drew Reese
2022-06-17