【问题标题】:ComponentDidUpdate usage and Maximum update depth exceeded超过 ComponentDidUpdate 使用和最大更新深度
【发布时间】:2019-06-20 15:23:48
【问题描述】:

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

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

不变违规:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

我当前计算水量的代码

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

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    当体重、年龄或性别发生变化时,我会完全避免 componentDidUpdate,即

    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 中没有针对sliderValue 的检查,所以它不会触发this.waterCalculator();。它不会因此导致无限循环
    • 同意您提出的解决方案更适合他的方案。赞成
    • 我有不同的函数来更新每个输入年龄、体重和性别等的状态。要使用您的解决方案,我需要创建 calcSliderValue 并在每个处理程序上调用此函数。对吗?
    • 谢谢 Isaac,好吧,既然你找到了技术原因,我也会对你做同样的事情:P @sinan 是的,在这种情况下,你会在每个函数中调用它,但请注意,如果你是检查状态值,您应该像我所做的那样使用第二个 arg 来调用它来 setState
    • 感谢 @Dominic 和 Isaac 提供的合作和解决方案。最终我删除了 componentDidUpdate 并在每个状态更新器函数上调用我的 waterCalculator 函数并将其用作第二个 arg
    【解决方案2】:
    componentDidUpdate(prevState) { // <===Error
    
    }
    
    

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

    解决问题

    componentDidUpdate(prevProps, prevState) {
      ...
    }
    

    只需将prevState 放入第二个参数

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 1970-01-01
      • 2021-07-12
      • 2019-04-03
      • 2019-02-14
      • 2019-07-17
      • 2019-12-13
      • 2019-05-28
      • 2019-12-03
      相关资源
      最近更新 更多