当状态是对象数组时更新状态。反应
Updating state when state is an array of objects. React
我正在使用上下文处理购物车以做出反应。我的问题是更改具有对象数组的状态。
我的数组看起来像这样[{itemId: 'ps-5', qty:4}, {itemId: 'iphone-xr', qty:2}]
这是我的代码查看评论
export const CartContext = createContext()
class CartContextProvider extends Component {
state = {
productsToPurchase: []
}
addProduct = (itemId)=> {
if (JSON.stringify(this.state.productsToPurchase).includes(itemId)){
// Add one to the qty of the product
this.state.productsToPurchase.map(product=>{
if (product.itemId === itemId){
// This is wrong I have to use setState(), but the syntax is a little bit complex
product.qty = product.qty + 1
}
})
}
else {
this.state.productsToPurchase.push({itemId: itemId, qty: 1})
}
}
render() {
return (
<CartContext.Provider value={{...this.state, addProduct: this.addProduct}}>
{this.props.children}
</CartContext.Provider>
)
}
}
export default CartContextProvider;
您是直接更新状态,但是您必须使用this.setState
来更新它,
现场演示
addProduct = (itemId) => {
this.setState((oldState) => {
const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
return {
productsToPurchase: !objWithIdExist
? [...oldState.productsToPurchase, { itemId, qty: 1 }]
: oldState.productsToPurchase.map((o) =>
o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
)
};
});
};
我正在使用上下文处理购物车以做出反应。我的问题是更改具有对象数组的状态。
我的数组看起来像这样[{itemId: 'ps-5', qty:4}, {itemId: 'iphone-xr', qty:2}]
这是我的代码查看评论
export const CartContext = createContext()
class CartContextProvider extends Component {
state = {
productsToPurchase: []
}
addProduct = (itemId)=> {
if (JSON.stringify(this.state.productsToPurchase).includes(itemId)){
// Add one to the qty of the product
this.state.productsToPurchase.map(product=>{
if (product.itemId === itemId){
// This is wrong I have to use setState(), but the syntax is a little bit complex
product.qty = product.qty + 1
}
})
}
else {
this.state.productsToPurchase.push({itemId: itemId, qty: 1})
}
}
render() {
return (
<CartContext.Provider value={{...this.state, addProduct: this.addProduct}}>
{this.props.children}
</CartContext.Provider>
)
}
}
export default CartContextProvider;
您是直接更新状态,但是您必须使用this.setState
来更新它,
现场演示
addProduct = (itemId) => {
this.setState((oldState) => {
const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
return {
productsToPurchase: !objWithIdExist
? [...oldState.productsToPurchase, { itemId, qty: 1 }]
: oldState.productsToPurchase.map((o) =>
o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
)
};
});
};