我試圖做一個計數器,加起來一個項目的總額添加到一個webcart。我在我的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
的狀態?
的可能的複製(https://stackoverflow.com/questions/45010544/react-cannot-read-property-of-undefined-despite-correct [作出反應,儘管正確結合「無法讀取的未定義的屬性」]綁定) –