gpt4 book ai didi

javascript - 用react.js类编写的BMI计算器需要在提交按钮上单击两次才能改变一些this.state值

转载 作者:行者123 更新时间:2023-12-01 01:06:08 25 4
gpt4 key购买 nike

我一直在开发一个用react.js类组件编写的BMI计算器,我发现第一次点击提交按钮不会改变一些this.state值,但第二次点击会改变所有值,我已阅读这些链接中的相关问题:

Pass values to child component on click submit button - ReactJS, click twice

ReactJS - Need to click twice to set State and run function

但我不知道如何向我的代码添加更改。这是我的代码:

import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props);
this.state = {fullName: '', weight: '', height: '', bmi: '', message: '', optimalWeight: ''};
this.handleChange = this.handleChange.bind(this);
this.calculateBMI = this.calculateBMI.bind(this);
this.handleSubmit =this.handleSubmit.bind(this);
}

handleChange(e){
this.setState({[e.target.name]: e.target.value});
}

calculateBMI(){
let heightSquared = (this.state.height/100 * this.state.height/100);
let bmi = this.state.weight / heightSquared;
let low = Math.round(18.5 * heightSquared);
let high = Math.round(24.99 * heightSquared);
let message = "";
if(bmi >= 18.5 && bmi <= 24.99){
message = "You are in a healthy weight range";
}
else if(bmi >= 25 && bmi <= 29.9){
message = "You are overweight";
}
else if(bmi >= 30){
message="You are obese";
}
else if(bmi < 18.5){
message="You are under weight";
}
this.setState({message: message});
this.setState({optimalWeight: "Your suggested weight range is between "+low+ " - "+high});
this.setState({bmi: Math.round(bmi * 100) / 100});
}


handleSubmit(e){
this.calculateBMI();
e.preventDefault();
console.log(this.state);

}

render(){
return(
<div className="App">
<div className="App-header">
<h2>BMI calculator</h2>
</div>
<form onSubmit={this.handleSubmit}>
<label>
Please enter your name
</label>
<input type="text" name="fullName" value={this.state.fullName} onChange={this.handleChange} />
<label>
Enter your height in cm
</label>
<input type="number" name="height" value={this.state.height} onChange={this.handleChange} />
<label>
Enter your weight in kg
</label>
<input type="number" name="weight" value={this.state.weight} onChange={this.handleChange} />
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}

export default App;

更新:

我还检查了问题Using async setState但我的问题不是以异步方式更新,但感谢@LMulvey,我确实通过分组 setState 并添加 console.log 作为回调函数来解决它 <强>计算BMI()

最佳答案

您的应用实际上运行得很好。问题是您试图在 setState 之前记录您的状态已经完全完成了。如果您附上您的console.log作为对您的最终 setState 的回调调用,您会发现它正在按预期工作。

this.setState({bmi: Math.round(bmi * 100) / 100}, () => console.log(this.state));

值得注意的是,您不需要 setState调用您正在更新的每个属性,您可以像这样将它们分组在一起,这也会导致您在此处出现竞争条件问题:

 this.setState({
bmi: Math.round(bmi * 100) / 100,
optimalWeight: "Your suggested weight range is between "+low+ " - "+high,
message
}, () => console.log(this.state));

关于javascript - 用react.js类编写的BMI计算器需要在提交按钮上单击两次才能改变一些this.state值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55618105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com