gpt4 book ai didi

javascript - ComponentDidUpdate 用法和超出最大更新深度

转载 作者:行者123 更新时间:2023-11-30 07:50:08 24 4
gpt4 key购买 nike

我有一个设置屏幕,我可以在其中获取用户的信息数量,例如年龄、体重和性别,然后根据这些信息计算用户每天应该喝多少水。

我想自动计算这个金额而不需要计算按钮。

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 });
};

这就是我想要自动更新水量的方式

  //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(prevState) { // <===Error

}

问题是 componentDidUpdate 中的第一个参数是 prevProps 而不是 prevState

解决问题

componentDidUpdate(prevProps, prevState) {
...
}

只需将 prevState 放入第二个参数

关于javascript - ComponentDidUpdate 用法和超出最大更新深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54388200/

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