当我点击[添加到购物车]按钮时,我收到错误消息:
。
我该如何解决这个问题?
这是我的full code link,下面是摘要,与问题相关:
class ProductsList extends Component {
....
renderProductsList() {
function mapProductCards(elem) {
return (
<Card className="m-1" style={{width: '18rem'}} key={elem.id}>
....
<CardText>isAvailable</CardText>
<Button onClick={() => this.props.addItemToCart(elem.id)}>Add to Cart</Button>
</CardBlock>
</Card>
)
}
....
this.props.products ....
.map(mapProductCards)
....
const mapDispatchToProps = (dispatch) => ({
....
addItemToCart(value) {
dispatch(addToCart(value));
}
....
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductsList);
....
答案 0 :(得分:1)
在renderProductsList函数的开头,将this
变量分配给本地变量。像这样:
renderProductsList() {
var that = this;
function mapProductCards(elem) {
return (
然后在需要的地方使用that
。例如,您的按钮现在是:
<Button onClick={() => that.props.addItemToCart(elem.id)}>Add to Cart</Button>
或者,使用箭头功能代替。像这样:
renderProductsList() {
mapProductCards = (elem) => {
return (
这将保留this
对您实际需要的对象的引用。
修改强>
根据您使用mapProductCards
函数的方式查看完整代码后,需要传入正确的对象以用作this
。您可以将该对象作为第二个参数传递给map
。像这样:
this.props.products.map(mapProductCards, this);
var new_array = arr.map(function callback(currentValue, index, array) { // Return element for new_array }[, thisArg])
thisArg:可选。执行回调时要使用的值。
答案 1 :(得分:1)
我也遇到了这个问题,问题是当我调试我的代码时,本地就是这个函数的这个对象给出了未定义的对象。你需要实例化函数 addItemToCart 的这个对象,因为当单击按钮,它会在控制台上显示错误
您的方法addItemToCart未定义 要克服这一点,你需要将本地定义为
renderProductsList() {
var localThis= this;
}
然后将您的方法称为
onClick={() => localThis.props.addItemToCart(elem.id)}
如果你在循环中使用一个函数说地图,那么你需要做
this.state.map(function(){
},**this**)
保留此