[英]I got this error => TypeError: Cannot read property 'image' of undefined
I am very new in this area and I searched in many places and could not find the solution.我在这个领域很新,我搜索了很多地方,找不到解决方案。 I get the error " TypeError: Cannot read property 'image' of undefined ".
我收到错误“ TypeError: Cannot read property 'image' of undefined ”。 I don't know where is the problem.The image of the error is here.
我不知道问题出在哪里。错误的图像在这里。
The class with the error is here.有错误的 class 在这里。
import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { detailsProduct } from '../actions/productActions';
function ProductScreen(props){
const productDetails = useSelector(state => state.productDetails);
const {product,loading,error} = productDetails;
const dispatch = useDispatch();
useEffect(() => {
dispatch(detailsProduct(props.match.params.id));
return () => {
//
}
}, [])
return <div>
<div className="back-to-result">
<Link to="/">Back to result</Link>
</div>
{loading?<div>Loading...</div>:
error? <div>{error}</div>:
(
<div className="details">
<div className="details-image">
<img src={product.image} alt="product"></img>
</div>
<div className="details-info">
<ul>
<li>
<h4>{product.name}</h4>
</li>
<li>
{product.rating} Stars ({product.numReviews} Reviews)
</li>
<li>
Price: <b>${product.price}</b>
</li>
<li>
Description:
<div>
{product.description}
</div>
</li>
</ul>
</div>
<div className="details-action">
<ul>
<li>
Price: {product.price}
</li>
<li>
Status: {product.status}
</li>
<li>
Qty: <select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</li>
<li>
<button className="button">Add to Cart</button>
</li>
</ul>
</div>
</div>
)
}
</div>
}
export default ProductScreen;
console.log(productDetails) is here console.log(productDetails) 在这里
Your variable product
isn't initialized.您的变量
product
未初始化。 As it looks You are loading it in background it might not be initialiazed on first load, but can be initialized later, therefore I would show loading
till it's initialized.看起来你正在后台加载它,它可能不会在第一次加载时初始化,但可以稍后初始化,因此我会显示
loading
直到它被初始化。 Do check like this before you use product
variable in Your code:在您的代码中使用
product
变量之前,请务必检查:
if (!product) {
return <div>Loading...</div>;
}
It's because it doesn't think, or know, that 'image' exists on 'product'.这是因为它不认为或不知道“图像”存在于“产品”上。 You can fix it with this minor change:
您可以通过以下小改动来修复它:
{product.image && <img src={product.image} alt="product" />}
You might still run into the same issue with all the other objects on product though.不过,对于产品上的所有其他对象,您可能仍会遇到相同的问题。 A better solution might be to destructure product to ensure the pieces exis:
更好的解决方案可能是解构产品以确保碎片存在:
const { image, name, rating, numReviews, price, description, status } = product;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.