[英]How to push new value into array of object in React
I think it might be silly question to ask but trust I am new to React.我认为问这个问题可能很愚蠢,但相信我是 React 新手。 I am trying to push new key and value to array of object but I am not able to do it.我正在尝试将新键和值推送到 object 数组,但我无法做到。 Could someone please help me how to achieve my goal.有人可以帮助我如何实现我的目标。 Thanks谢谢
Code代码
this.state= {
cartItems=[
{name:'item1',price:'$23'},
{name:'item2',price:'$26'},
{name:'item3',price:'$24'},
]
I want to add new value like quantity:0
in the end of array of object.我想在 object 的数组末尾添加新的值,例如quantity:0
。 Please help me请帮我
If you want to update state adding a property to each object, you should just use setState
in combination with map
.如果你想更新 state 为每个 object 添加一个属性,你应该将setState
与map
结合使用。 Array.prototype.map
allows you to transform each object, like this: Array.prototype.map
允许您转换每个 object,如下所示:
this.setState(state => {
cartItems: state.cartItems.map(cartItem => ({
...cartItem, // Keep all old properties
quantity: 0 // Add quantity
})
})
You should do this only if you're calling setState
after the initializer .只有在初始化器之后调用setState
时,才应该这样做。 If you need to modifiy the data right when assigning to this.state
, just map the array directly.如果您需要在分配给this.state
时修改数据,直接使用 map 数组即可。
Maybe try this也许试试这个
const newState = this.state.cartItems.map(item => {
item.quantity = 0;
return item;
});
this.setState({cartItems: newState});
this.state= {
cartItems:[
{name:'item1',price:'$23'},
{name:'item2',price:'$26'},
{name:'item3',price:'$24'},
]
}
updateCartItems=()=>{
var cartItems = this.state.cartItems.map((item)=>{
return {...item,quantity:0}
})
this.setState({cartItems})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.