我收到一个无法读取的undefined道具。我正在尝试破坏道具,但我需要挂接呼叫。我是否可以通过某种方法来分解道具的功能,或者通过其他方式来解决此问题?
ProductBrowse.jsx正在格式化产品:
const ProductBrowse = () => {
const { id, name, img, store, price, desc, inCart } = this.props.product;
const [open, setOpen] = React.useState(false);
const openModal = () => {
setOpen(!open);
};
const closeModal = () => {
setOpen(!open);
};
return (
<Box border={1} borderRadius={3}>
<Card>
<CardActionArea>
<ProductModal
open={open}
onClick={() => openModal()}
onClose={() => closeModal()}
onSave={() => closeModal()}
productName={name}
productDesc={desc}
/>
<CardHeader
title={name}
subheader={formatCurrency(price)}
/>
<CardMedia
image={img}
alt={desc}
/>
<CardContent>
<Typography variant='body2' color='textSecondary' component='p'>
{desc}
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button size='small' /*To Checkout*/>BUY NOW</Button>
<Button
size='small'
onClick={() => {
console.log('Added to Cart');
}}
>
ADD TO CART
</Button>
<Button size='small'>REVIEW</Button>
</CardActions>
</Card>
</Box>
);
}
答案 0 :(得分:1)
您可以将基于类的组件转换为这样的功能组件:
const ProductBrowse = ({ product }) => {
const { id, name, img, store, price, desc, inCart } = product;
...
}
export default ProductBrowse;
如您所见,产品道具正在被破坏。如果您要提供更多的道具并且也想使用它们,则可以使用整个道具对象。
即
const ProductBrowse = (props) => {
const { id, name, img, store, price, desc, inCart } = props.product;
...
}
export default ProductBrowse;
答案 1 :(得分:1)
您正在尝试在基于类的组件中使用钩子。请参阅converted functional component
const ProductBrowse = props => {
const { id, name, img, store, price, desc, inCart } = props.product;
const [open, setOpen] = useState(false);
const classes = useStyles();
const openModal = () => {
setOpen(!open);
};
const closeModal = () => {
setOpen(!open);
};
return (
<Box border={1} borderRadius={3}>
<Card>
<CardActionArea>
{<ProductModal
open={open}
onClick={() => openModal()}
onClose={() => closeModal()}
onSave={() => closeModal()}
productName={name}
productDesc={desc}
/> }
<CardHeader title={name} subheader={formatCurrency(price)} />
<CardMedia image={img} alt={desc} />
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">
{desc}
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button size="small" /*To Checkout*/>BUY NOW</Button>
<Button
size="small"
onClick={() => {
console.log("Added to Cart");
}}
>
ADD TO CART
</Button>
<Button size="small">REVIEW</Button>
</CardActions>
</Card>
</Box>
);
};
在使用ProductBrowse组件进行销毁时,还可以在使用此组件时传递产品作为道具。应该是这样的:
<ProductBrowse products={this.products} />