如何在函数中访问State内的键值?

时间:2017-08-02 01:16:53

标签: javascript html reactjs

我正在尝试制作一个计数器,用于累计添加到网络摄像头的项目的总金额。我在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状态?

2 个答案:

答案 0 :(得分:4)

使用箭头功能以保留this

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

答案 1 :(得分: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};
}