当我增加一个商品数量并点击添加按钮时,该商品将成功添加到购物车中。但是,当我先增加两个或三个商品的数量,然后再单击添加按钮时,相应的商品数量计数与增加的值不匹配。
完整代码在这里 -https://github.com/sivadass/react-shopping-cart 我认为问题出在Counter.js中,它没有在增加数量后将先前状态设置为最新状态,以便稍后添加到购物车中。
完整代码在这里 -https://github.com/sivadass/react-shopping-cart 我认为问题出在Counter.js中,它没有在增加数量后将先前状态设置为最新状态,以便稍后添加到购物车中。
import React, { Component } from "react";
import PropTypes from "prop-types";
class Counter extends Component {
constructor(props) {
super(props);
this.state = { value: this.props.productQuantity };
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment(e) {
this.setState(
prevState => ({
value: Number(prevState.value) + 1
}),
function() {
this.props.updateQuantity(this.state.value);
}
);
e.preventDefault();
}
decrement(e) {
e.preventDefault();
if (this.state.value <= 1) {
return this.state.value;
} else {
this.setState(
prevState => ({
value: Number(prevState.value) - 1
}),
function() {
this.props.updateQuantity(this.state.value);
}
);
}
}
feed(e) {
this.setState(
{
value: this.refs.feedQty.value
},
function() {
this.props.updateQuantity(this.state.value);
}
);
}
resetQuantity() {
this.setState({
value: 1
});
}
render() {
return (
<div className="stepper-input">
<a href="#" className="decrement" onClick={this.decrement}>
–
</a>
<input
ref="feedQty"
type="number"
className="quantity"
value={this.state.value}
onChange={this.feed.bind(this)}
/>
<a href="#" className="increment" onClick={this.increment}>
+
</a>
</div>
);
}
}
Counter.propTypes = {
value: PropTypes.number
};
export default Counter;
index.js
中更改顶层的数量,并将其作为props传递给每个“Product”。你需要将它删除,并独立处理每个“Product”的“quantity”。 - Asaf Aviv