【问题标题】:How to access a key value within State in a function?如何在函数中访问 State 中的键值?
【发布时间】: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


【解决方案1】:

使用箭头函数以保留this

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

【讨论】:

    【解决方案2】:

    你需要绑定你的函数,才能访问函数体中的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};
    }
    

    【讨论】:

    • 啊!对。谢谢。
    • 当然,不要忘记forEach中的上下文
    • 是的,我正要问你,我应该如何将它传递给forEach 函数?
    • let self = this; this.state.cart.forEach(function(item, index){ var total = self.state.total; self.state.total = self.state.total + item.price; })
    • @feners 你应该按照 Josiah 的回答使用箭头函数,并且你不需要绑定你的函数。
    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 2018-07-26
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多