反应中出现错误:第25行:未定义'totalIncome'no-undef

时间:2019-03-07 21:50:48

标签: html reactjs components jsx

import React, {Component} from 'react'

class CalculateIncome extends Component {
        state = {
            totalIncome:0
        }

        calculation = () => {
            this.props.lessons.filter(lesson => {
                this.props.clients.filter(client => {
                    if (client.name === lesson.name){
                        let income = client.price * lesson.time;
                        let totalIncome = this.state.totalIncome + income
                        return(
                            totalIncome
                        )
                    }
                    return (
                        this.setState({
                            totalIncome : totalIncome   //this is the error
                        })
                    )
                })      
                return (this.state.totalIncome)
            })
        }

        render() {
            console.log(this.props.lessons, this.props.clients) //this checks out!
            return ( this.props.lessons.length ? 
            (
                <div onLoad={this.calculation}>{this.state.totalIncome}</div>
            )  
                : 
            (<div className="text-center my-5">You are broke</div>) 
        )
    }
}

export default CalculateIncome

App.js中的道具正在正确加载,因为我在进行console.log()时可以看到它们的显示。

此计算的总体目的是接受新添加的课程,并在现有客户列表中进行遍历,并将课程的时间或持续时间乘以客户列出的价格,这样我才能获得收入。然后,我想将该个人收入添加到总收入中并显示出来。

我遇到了未定义的错误,或者我四处走动时出现“需要返回值”错误。我是新手,所以我很困惑。任何帮助,将不胜感激,谢谢!如果您需要更多我的组件,请告诉我。

1 个答案:

答案 0 :(得分:0)

我认为您根本不需要使用状态进行此计算(如果按照您尝试的方式进行操作,则每次客户端课程匹配时,组件都会重新渲染。这是一个快速的(未经测试)您可以做到的方式。

import React, { PureComponent } from 'react'

class CalculateIncome extends PureComponent {
        calculation = () => {
            const { lessons = [], clients = [] } = this.props;
            let totalIncome = 0;
            lessons.forEach(lesson => {
                clients.forEach(client => {
                    if (client.name === lesson.name) {
                        totalIncome += client.price * lesson.time;
                    }
                });
            });
            return totalIncome;
        }

        render() {
            const { lessons } = this.props;

            if (lessons.length) {
                const totalIncome = this.calculation();
                return <div>{totalIncome}</div>;
            }
            return <div className="text-center my-5">You are broke</div>;
        )
    }
}

export default CalculateIncome;