2017-08-02 25 views
1

我試圖做一個計數器,加起來一個項目的總額添加到一個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的狀態?

+0

的可能的複製(https://stackoverflow.com/questions/45010544/react-cannot-read-property-of-undefined-despite-correct [作出反應,儘管正確結合「無法讀取的未定義的屬性」]綁定) –

回答

4

使用箭頭功能,使this被保留。

this.state.cart.forEach((item, index) => { 
    // ... 
}) 
1

你需要綁定你的功能,讓函數體訪問this

constructor(props) { 
    super(props); 
    this.itemBucket = this.itemBucket.bind(this); 
    this.countTotal = this.countTotal.bind(this); 
    this.state = {items: this.props.cart,cart: [],total: 0}; 
} 
+0

啊!對。謝謝。 – feners

+0

@feners,你的歡迎:) – Andrew

+0

當然,不要忘記在'forEach'上下文 – Andrew

相關問題