【发布时间】:2017-08-02 01:16:52
【问题描述】:
我正在尝试制作一个计数器,用于计算添加到网络购物车的商品的总金额。我在 this.state 构造函数中初始化了这个计数。但是,我在从同一组件中的函数向其推送计数总数时遇到问题。这是我的Cart 组件:
import React, { Component } from 'react';
import {addCart} from './Shop';
import { connect } from 'react-redux';
export class Cart extends Component {
constructor(props) {
super(props);
this.state = {items: this.props.cart,cart: [],total: 0};
}
itemBucket(item) {
this.state.cart.push(this.state.items);
this.countTotal();
}
countTotal() {
console.log(this.state.cart);
this.state.cart.forEach(function(item, index){
var total = this.state.total;
this.state.total = this.state.total + item.price;
})
}
...
render() {
return(
<div className= "Webcart" id="Webcart">
</div>
);
}
}
...
在我的countTotal 函数中,我想将总数推送到this.state.total。现在我收到此错误Uncaught TypeError: Cannot read property 'state' of undefined。如何在状态下将计数总数推送到total?
【问题讨论】:
标签: javascript html reactjs