我正在使用一个 reactjs 计算器应用程序。它应该像一个简单的手持计算器一样工作。到目前为止,我已经设法捕获并显示第一和第二操作数的用户输入以及要执行的操作(+,-,/,*)使用状态和setState。当我按下“equals”按钮时,麻烦就来了,它应该调用我称之为EqualsSign()的函数,以便获得答案并将其显示在屏幕上。无论我输入什么数字,我都得到0作为答案。代码如下:EqualsSign(){ this.A=parseFloat(this.state.operand) console.log("A is ",this.A)// debuging line this.B=parseFloat(this.state.operand2) console.log("B is ", this.B) switch(this.state.operation){ case "+": console.log(this.state.operation) this.setState({answer: (this.A+this.B).toString()}, console.log(this.state.answer)) this.setState({operand: this.state.answer, operand2: '', operation: ''}) break case "-": console.log(this.state.operation) this.setState({answer: this.A+this.B}, console.log(this.state.answer)) this.setState({operand: this.state.answer, operand2: '', operation: ''}) break case "*": console.log(this.state.operation) this.setState({answer: this.A+this.B}, console.log(this.state.answer)) this.setState({operand: this.state.answer, operand2: '', operation: ''}) break case "÷": console.log(this.state.operation) this.setState({answer: this.A+this.B}, console.log(this.state.answer)) this.setState({operand: this.state.answer, operand2: '', operation: ''}) break default: // }}计算应用和控制台日志的屏幕截图,显示 0 作为 A+B 的输出(A=15,B=12你能帮忙吗,我在这里做错了什么?
1 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
你的错误就在这里
this.setState({answer: (this.A+this.B).toString()}, console.log(this.state.answer))
当您尝试显示 this.state.answer 时,答案尚未更新。
尝试将控制台.log传递给 cb:
this.setState({answer: (this.A+this.B).toString()}, () => console.log(this.state.answer))
添加回答
举报
0/150
提交
取消