[英]how to pass values from an array into a prop
so im trying to pass the value price from this array所以我试图从这个数组中传递价值价格
const [products, setProducts] = useState(
[{
name: "14K bracelet",
id: "1",
description: "Beautfull 14K gold Bracelet",
price: 100.00,
img: braceletImg,
}]
)
into here到这里
<h1 className="price">{products.price}</h1>{/*this is a prop*/}
I call the prop here in cart我在购物车中调用道具
function Cart({ products })
full code of the cart component购物车组件的完整代码
function Cart({ products }) {
return(
<div className="Body">
{/* {products.map(pr => <h1 className="price">{pr.price}</h1>)} */}
<div className="Cart-wrapper" >
<div className="cart-header">
<h5 className="Product-name cart-text">Product</h5>
<h5 className="quantity-name cart-text">Quantity</h5>
<h5 className="price-name cart-text">Price</h5>
<Button className="btn btn-plus">+</Button>
<Button className="btn btn-minus">-</Button>
<div className="card-cart">
<img className="braceletimg" src={braceletImg} />
<h1 className="card-body-title">Bracelet title</h1>
<h1 className="card-body-title seemore"><Link className="Link" to="/Bracelets">Learn More</Link></h1>
<hr className="cart-hr"></hr>
</div>
<div className="div-price">
{products.map(pr => <h1 key={pr.id} className="price">{pr.price}</h1>)}
<small className="shippingprice">$5.00 + shipping</small>
</div>
<Button className="btn btn-cart btn-primary"><Link className="Link" to="/Cart/shipping-buynow">Review Cart</Link></Button>
</div>
</div>
</div>
)
}
export default Cart;
hopefully, this gives you a better context of the component希望这可以为您提供更好的组件上下文
Because products
is an array , you either need to use indexing, or you can process them all using .map()
.因为
products
是一个数组,所以您要么需要使用索引,要么可以使用.map()
处理它们。
Using indexing:使用索引:
<h1 className="price">{products[0].price}</h1>
Using .map()
:使用
.map()
:
{products.map(pr => <h1 key={pr.id} className="price">{pr.price}</h1>)}
The addition of key={...}
is needed so React can optimize the rendering.需要添加
key={...}
以便 React 可以优化渲染。 If you don't add it then React will show warnings in the console output.如果你不添加它,那么 React 将在控制台 output 中显示警告。 If the items already have a unique id or key value, then it's best to use that.
如果项目已经有唯一的 id 或键值,那么最好使用它。
Update:更新:
Your Cart
component may be getting activated already before products
has been initialized, this would explain the undefined
errors.您的
Cart
组件可能在products
初始化之前就已经被激活,这可以解释undefined
的错误。
This is quite normal, and to prevent it from being a problem you can check if products
is empty:这是很正常的,为了防止它成为问题,您可以检查
products
是否为空:
function Cart({ products }) {
if (!products)
return "Loading...";
return (
// ...
// ...
// ...
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.