axios 为什么React - component在从服务器获取img src路径之前加载?

kyxcudwk  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(127)

在这里,我通过axios和@reduxjs/toolkit从本地服务器获取数据,下面的代码运行良好。

function ProductDetails() {
    let dispatch = useDispatch();
    let productsState = useSelector((state) => state.products);
    let prodId = useParams().id;
    useEffect(() => {
        dispatch(fetchProductDetails(prodId));
    }, [dispatch, prodId]);
    let { product, loading, error } = productsState;
    return (
        <Fragment>
            <div className="productDetails">
                <div className="productDetails__left">
                    <p>{product.name}</p>
                </div>
            </div>
        </Fragment>
    );
}

export default ProductDetails;

Redux商店运作得很好,没什么问题
合理的回应:-

{
    "success": true,
    "product": {
        "_id": "62d26e1c19177452c1db9d30",
        "user": "62cd4f2941c20f69eb61d163",
        "name": "HP Pavilion Gaming Laptop",
        "description": "Top perfomance gaming laptop",
        "price": 50000,
        "category": "gaming laptop",
        "ratings": 5,
        "images": [
            {
                "public_id": "placeholder",
                "url": "https://www.reliancedigital.in/medias/HP-15-ec2008AX-Laptops-491997441-i-1-1200Wx1200H-96Wx96H?context=bWFzdGVyfGltYWdlc3w4ODc1OHxpbWFnZS9qcGVnfGltYWdlcy9oMzUvaDhkLzk2MjgyMDUxMjE1NjYuanBnfDY4NGUzYmViMTY3NzM1Mzk3ZmQ4OTA1ZmZlZDAxYmJkNWYwNzUwMTBmMTg3ZDdkNWM1NDJkYWY5MzMyMzExNDc",
                "_id": "62d26e1c19177452c1db9d31"
            }
        ],
        "stock": 19,
        "numOfReviews": 1,
        "reviews": [
            {
                "user": "62d2712709be7c1ae9363ee6",
                "name": "Brenden McCullam",
                "rating": 5,
                "comment": "cool stuff,again!!!",
                "_id": "62d2714b09be7c1ae9363eec"
            }
        ],
        "created_at": "2022-07-16T07:51:56.757Z",
        "__v": 3
    }
}

...但是在div中添加下面一行代码时会给出下面的错误。

<img src={product.images[0].url} alt="product" />

错误:

ProductDetails.jsx:20 Uncaught TypeError: Cannot read properties of undefined (reading '0')
    at ProductDetails (ProductDetails.jsx:20:1)
    at renderWithHooks (react-dom.development.js:16305:1)
    at mountIndeterminateComponent (react-dom.development.js:20074:1)
    at beginWork (react-dom.development.js:21587:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at beginWork$1 (react-dom.development.js:27451:1)
    at performUnitOfWork (react-dom.development.js:26557:1)
    at workLoopSync (react-dom.development.js:26466:1)

将上面的代码行替换为下面的代码行也可以正常工作:

{product.images ? <img src={product.images[0].url} alt="product" /> : null}

---或者---

{!loading ? <img src={product.images[0].url} alt="product" /> : null}

所以很明显,当组件加载img时,srcproduct.image并不存在。但是product.name和其他所有东西都存在。为什么会发生这种情况?我应该总是用if条件 Package 我的整个组件吗?这是正确的方法吗?请帮助?

f45qwnt8

f45qwnt81#

我猜product在提取完成之前是一个空对象,因为它在product.name处不抛出。
输出product.name不会抛出错误,因为React会默认地将结果undefined视为没有内容。然而,尝试索引product.images会抛出错误,因为您正在尝试访问undefined上的属性。
是的,如果输出试图访问nullundefined,则应该将输出 Package 在条件中,或者将值传递给在内部处理空值情况的组件。

<div>
  {product.images &&
    <img src={product.images[0].url} alt="product" />
  }
  <OptionalProductImage product={product} /> 
</div>
68de4m5k

68de4m5k2#

添加三元表达式以检查URL,如果当前不存在,则使用临时图像,直到获得产品图像。

<img src={product?.images?.[0]?.url || tempImage} alt="product" />

相关问题