【发布时间】:2017-11-06 13:48:49
【问题描述】:
我正在使用 setState 来更新特定对象,但由于某种原因,即使我没有在 setState 函数中添加另一个对象,它也会发生变异。
基本上我有一个“添加到购物车”功能,如果购物车状态对象中已经存在商品,只需将其数量增加 1。如果没有,使用包含所述商品的副本更新购物车状态。
this.state = {
items: {
0: { name: 'Red shirt', price: 10 },
1: { name: 'Blue shirt', price: 11 },
2: { name: 'Green shirt', price: 12 },
3: { name: 'Yellow shirt', price: 13 }
},
cart: {},
user: {}
}
addToCart = (key, item) => {
let newCart;
newCart = this.state.cart;
// item already exists in cart
if (newCart[key]) {
// increment qty of added item
newCart[key].qty++;
// does not exist, need to add to cart
} else {
newCart[key] = item;
newCart[key].qty = 1;
}
this.setState({ cart: newCart });
}
render() {
const { cart, items } = this.state;
return (
<div className="App">
<h1>Streat</h1>
<Checkout cart={cart} />
<Items
items={items}
addToCart={this.addToCart}
/>
</div>
);
}
}
// Items component which holds Item component
class Items extends Component {
constructor(props) {
super(props)
}
render() {
const { items, addToCart } = this.props;
return (
<div>
{
map(items, function renderItems(item, key) {
return <Item
item={item}
itemRef={key}
key={key}
addToCart={addToCart} />
})
}
</div>
)
}
}
// Item functional component which has the add to cart button
const Item = (props) => {
const { item, itemRef, addToCart } = props;
return (
<div>
<p>{item.name}</p>
<p>{item.price}</p>
<p>{item.qty || ""}</p>
<button onClick={() => addToCart(itemRef, item)}>Add</button>
</div>
)
}
在 react 开发人员工具中检查我的 items 对象的状态时,我看到每次单击按钮将商品添加到购物车时,它都会正确地将商品添加到购物车/更新商品的数量,但是它还会在我的状态下更新项目对象中的项目,添加一个“数量”键/值对,这不是我想要的。
我在我的购物车对象上使用了 setState,但我的 items 对象也因某种原因被更改了。
【问题讨论】:
-
你能加你总码吗
-
@Geeky 完成 :)!
标签: reactjs