javascript - 反应增量和减量计数
问题描述
import {
ProductCycleContextProvider,
ProductContext,
} from '../contexts/productCycleContext';
class Cart extends Component {
static contextType = ProductContext;
constructor(props) {
super(props);
this.state = {
selectedForCart: [],
checkOut: true,
grandTotal: undefined,
};
}
async componentDidMount() {
await axios
.get('http://localhost:80/newItem/storeIntoCart')
.then((res) => {
res.data.map((i) => {
this.context.setCart(i);
});
})
.catch((e) => alert(e));
}
remove = () => {
console.log('remove');
};
increment = (v, i) => {
axios
.patch(`http://localhost:80/cart/cartCustomize/${i}`, {
quantity: v,
})
.then((res) => {
const ind = this.context.cart.findIndex((x) => x._id === res.data._id);
this.context.cart[ind] = res.data;
})
.catch((e) => console.log(e));
};
decrement = (v, i) => {};
render() {
return (
<div>
{this.context.cart &&
this.context.cart.map((v, i) => {
return (
<Container className="mt-5" key={i}>
<Row>
<Col lg={2} md={2} sm={12}>
<h5>
<b>{v.title}</b>
</h5>
<img
src={v.photo}
style={{
border: '2px solid black',
borderRadius: '5px',
width: '100px',
height: '80px',
}}
/>
</Col>
<Col lg={2} md={2} sm={12}>
<p>
Price: ₹
{v.priceTaxIncluded}
</p>
<p style={{fontSize: '10px'}}>Tax inclusive</p>
</Col>
<Col lg={2} md={2} sm={12}>
<Row>
<Button
value={v.quantity}
onClick={(e) => {
const val = e.target.value;
const id = v._id;
this.decrement(val, id);
}}>
-
</Button>
{v.quantity}
<Button
value={v.quantity}
onClick={(e) => {
const id = v._id;
let val = Number(e.target.value);
let q = val + 1;
this.increment(q, id);
}}>
+
</Button>
</Row>
</Col>
<Col lg={2} md={2} sm={12}>
<br></br>
<Button
className="btn btn-warning mt-2"
size="sm"
onClick={this.remove}>
Remove
</Button>
</Col>
<Col lg={2} md={2} sm={12}>
{this.state.checkOut && (
<>
<p>{v.priceTaxIncluded * v.quantity}</p>
</>
)}
</Col>
<Col lg={2} md={2} sm={12}></Col>
</Row>
</Container>
);
})}
</div>
);
}
}
在此代码中,单击增量时,我需要将产品数量加一。这个数量应该乘以价格。它正在发生,但如果我第一次增加,那么它不会显示任何内容,第二次它增加并显示以前的值,第三次点击它显示第二次点击的值......就像它一样。 ..我应该单击增量按钮 2 次 我应该使用组件确实更新...但是第一次渲染它?
解决方案
ProductContext
如果手动更新,则不应更新购物车属性。而是使用ProductContext
其中的一个函数setState
来通知 React 状态的变化。
increment = (v, i) => {
axios
.patch(`http://localhost:80/cart/cartCustomize/${i}`, {
quantity: v,
})
.then((res) => {
this.context.setCartItem(res.data);
})
.catch((e) => console.log(e));
};
在您的提供者/上下文中:
setCartItem(cartItem) {
const ind = this.state.cart.findIndex((x) => x._id === cartItem._id);
const updatedCart = [...this.state.cart][ind] = cartItem;
this.setState(updatedCart);
}
推荐阅读
- java - 如何使用 apache camel dsl 删除 csv 的标头
- c - 如何修复“调试错误!,变量'x'周围的堆栈已损坏”?
- azure - AS2 消息接收器
- wpf - 用于编辑数据网格的复杂属性的弹出窗口
- java - 将 ES 查询转换为按键和值对嵌套对象进行排序到 Java API(ES 版本 6.2)的问题
- python - 我可以在 python 函数中读取 Excel 文件时锁定它吗?
- git - 错误消息:第一次为新项目克隆存储库时目录名称无效
- python - 2x 嵌套函数中的访问列表
- image - 为什么不在 ie 11 和 Firefox 中“将图像另存为”调用操作方法?
- java - 扫描仪需要输入两次才能继续