【问题标题】:After upgrading to React 16 componentDidUpdate causing an infinite loop when calling redux-form action creator升级到 React 16 后 componentDidUpdate 在调用 redux-form action creator 时导致无限循环
【发布时间】:2019-08-06 15:13:41
【问题描述】:

我有一个表单,我想在加载组件时跨字段运行数学计算。

如果用户从下拉列表中选择“网格”,则字段会根据一组默认值进行计算。如果用户更改任何字段的值,它会根据输入的每个新值重新计算。

在升级到 React 16、15 和 Redux-Form 7+ 到 8 之前,这是通过在 componentWillUpdate 生命周期方法中调度 redux-form 动作创建者来实现的。现在,它会导致无限循环。

我已从 componentWillUpdate 方法更新为迁移到 React 16 时建议的首选 componentDidUpdate 方法。

正如文档在设置状态时建议的那样,我在方法中放置了一个条件,但是当我这样做时,该方法会继续调用自身。

我尝试了各种其他方法,包括 onChange 处理程序,但我需要在每次击键后渲染组件之前计算这些值。

// here is the conditional for when the user selects grid in a drop-down, and the other to compare a field called gredThetaIncrement when a user inputs a new value. There are several other fields I need to compare as well, but it fails even when testing with one.

  componentDidUpdate(prevProps, prevState) {
    if (this.props.thetaDistribution === 'grid' && prevProps.gridThetaIncrement !== this.props.gridThetaIncrement) {
      this.calculateThetaPointsAndTestTakers(this.props)
    }
    return null;
  }
// method to handle the calculations, where using a redux-form action creator is calling setState() and no doubt causing the infinite loop

  calculateThetaPointsAndTestTakers(props) {
    const {
      thetaLowerBound,
      thetaUpperBound,
      gridThetaIncrement,
      gridTestTakersPerTheta,
      thetaDistribution,
    } = props;

    const { dispatch } = this.props;
    const multiplier = Math.max(
      findMultiplier(thetaUpperBound - thetaLowerBound),
      findMultiplier(gridThetaIncrement)
    );
    const totalThetaPoints =
      Math.trunc(
        ((thetaUpperBound - thetaLowerBound) * multiplier) /
        (gridThetaIncrement * multiplier)
      ) + 1;

    const testTakerCount = totalThetaPoints * gridTestTakersPerTheta;

    dispatch(change('simulationForm', 'totalThetaPoints', totalThetaPoints));
    dispatch(change('simulationForm', 'testTakerCount', testTakerCount));
  }

结果应该是在每次输入新值后跨 redux-form 字段更新的计算。

这里是破解代码的沙盒。 https://codesandbox.io/embed/redux-form-template-jhrn7?fontsize=14

在下拉菜单中选择“网格”,无限循环将打破页面。

感谢任何帮助理解 componentDidUpdate 或如何实现这一点。我有 4 个不同的字段需要根据用户输入来计算值。对每个输入调用计算方法的每个 onChange 方法似乎是多余的。我敢肯定有更好的方法我只是没有意识到。

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    gridThetaIncrement改变时,你触发calculateThetaPointsAndTestTakers,它派发props(触发componentDidUpdate但不满足条件),然后触发你的字段的onChange,包括thetaDistribution,它触发他的@ 987654326@方法,调用handleThetaDistributionChange,调度gridThetaIncrement,调用componentDidUpdate并满足你的条件,再次开始循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2021-09-07
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多