我试图打开产品卡上的产品详细信息页面onClick,当我从浏览器返回时,我希望能够点击另一个产品卡与onClick导致它的产品详细信息页面,但我得到这个类型错误。"details"是一个数组,它有时可能是空的,但有一个条件product['details'],只有在它为真时才渲染,而不是我得到一个错误
const [ dataLoad, holdRender ] = useState(false); //hold render until data is ready
const [ product, setProduct ] = useState({});
const [ currentProduct, setCurrentProduct ] = useState(0);
//this useEffect runs once
useEffect(()=> {
(async () => {
//set params id received so whenever it updates the data is updated
const productId = await props.getProduct(props.match.params.id);
setCurrentProduct(productId);
})();
}, []);
//this useEffect runs everytime the params id is received/changed
useEffect(() => {
//get data from the backend to update UI in time until then hold
(async () => {
const data = await props.security.product.data;
setProduct(data);
})();
//if product.details is now available
if(product['details']){
//let go of render
holdRender(true);
}
else{
return null;
}
return () => {
setCurrentProduct(0);
};
}, [currentProduct]);
return(
<div>
{dataLoad !== false?
<div>
<Row>
<Col>
<Jumbotron id="productStatsCard">
<div className="productStats">
<h2>{product? product['details_not_verified']: <Loader/>}</h2>
</div>
</Jumbotron>
</Col>
<Col>
<Jumbotron id="productStatsCard">
<div className="productStats">
<h2>{product? product['details_verified']: <Loader />}</h2>
</div>
</Jumbotron>
</Col>
</Row>
<Row className="mt-5">
<Col sm={8}>
<Row>
<Col>
<div className="pdtTableContainer">
<div>
<Table>
<thead>
<tr>
<th>Category</th>
<th>Product Id</th>
<th>Product Name</th>
<th>Product Type</th>
</tr>
</thead>
<tbody>
{dataLoad && product['details']? product['details'].map(detail => (
<tr key={product.id}>
<td>
{product.category}
</td>
<td>{product.id}</td>
<td>
{product.product_title}
</td>
<td>{product.product_type}</td>
</tr>
)) : 'No products to display'}
</tbody>
</Table>
</div>
</div>
</Col>
</Row>
</Col>
</Row>
</div>: <Loader/>}
</div>
)
}
const mapStateToProps = (state) => ({
security: state.security,
});
export default connect(mapStateToProps, { getProduct })(productOverview);```
使用可选的链接操作符:
if(product?.['details']){
//let go of render
holdRender(true);
}
顺便说一下,您可以访问details
点符号:
if(product?.details){
//let go of render
holdRender(true);
}