超出 ComponentDidUpdate 使用和最大更新深度 [英] ComponentDidUpdate usage and Maximum update depth exceeded
问题描述
我有一个设置屏幕,我可以从用户那里获得一些信息,例如年龄、体重和性别,然后根据这些信息计算用户每天应该喝多少水.
I have a setting screen where I get number of info from user such as age, weight and gender and after this info I am calculating how much water user should drink per day.
我想自动计算此金额,无需任何计算按钮.
I would like to calculate this amount automatically without any need of calculate button.
不变违规:超过最大更新深度.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,就会发生这种情况.React 限制嵌套更新的数量以防止无限循环.
Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
我当前计算水量的代码
//function to calculate how much water to drink
waterCalculator = () => {
//let weightPound = this.state.weight * 2.2046;
let weightValue = this.state.weight;
let ageValue = this.state.age;
let waterAmount = null;
if (ageValue < 30) {
waterAmount = weightValue * 40;
} else if (ageValue >= 30 || ageValue <= 55) {
waterAmount = weightValue * 35;
} else {
waterAmount = weightValue * 30;
}
this.setState({ sliderValue: waterAmount });
};
这就是我想自动更新水量的方式
This how I want to automatically update my water amount
//checking if age and weight and gender states are changed call the function
componentDidUpdate(prevState) {
if (
this.state.age !== prevState.age &&
this.state.weight !== prevState.weight &&
this.state.gender !== prevState.gender
) {
this.waterCalculator();
}
}
推荐答案
当体重、年龄或性别发生变化时,我会完全避免 componentDidUpdate,即
I would avoid componentDidUpdate entirely by doing it when weight, age, or gender changes i.e.
onChange = name = e => {
this.setState({ [name]: e.target.value }, this.calcSliderValue);
}
calcSliderValue = () => {
if (all_inputs_are_filled) {
this.setState({ sliderValue: x });
}
}
<yourGenderInput onChange={this.onChange('gender')} ... />
<yourAgeInput onChange={this.onChange('age')} ... />
这篇关于超出 ComponentDidUpdate 使用和最大更新深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!