【发布时间】:2019-07-29 21:42:24
【问题描述】:
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(); 时我可以看到它们出现了
此计算的总体目的是获取添加的新课程并在现有客户列表中运行它,并将课程的时间或持续时间与客户列出的价格相乘,这样我就可以获得收入。然后我想将个人收入添加到总收入中并显示出来。
我得到一个未定义的错误,或者如果我移动东西我得到一个“需要返回值”错误。我是新手,所以我很困惑。任何帮助将不胜感激,谢谢!如果您需要更多我的组件,请告诉我。
【问题讨论】:
-
将你的计算()移动到componentDidMount(),请参阅反应生命周期方法。(reactjs.org/docs/react-component.html#componentdidmount)你要做的是1.从app.js获取道具2.执行计算(CdM() ) 3. 基于计算的渲染错误是:你已经返回 this.setState(xyz)。但该方法不返回任何内容。
-
我不明白你想用“this.props.clients.filter”做什么,也许你应该使用reduce来只返回一个值。无论如何,我认为您在计算器上的 setState 中的“totalIncome”没有定义。
-
@EdisonJunior 我的思考过程是筛选每节课,每节课都会筛选现有客户列表,直到找到与相同名称匹配的客户。在那里我会做数学计算,然后将答案发回并将其添加到 totalIncome。
标签: html reactjs components jsx