重复更新状态 - ReactJs

Updating state repeatedly - ReactJs

嗨,我有一个父组件,有两个子组件,如下所示,Child1 有可拖动的 div 元素,在拖动时它为父组件提供价值,然后我必须传递给 Child2 并使用,但是在 Child2 中使用它之前,我必须进行大量计算。

const Parent = () => {
  const [dragValue, setDragValue] = useState(0);
  const dragHanlder = (dragVal) => {
     setDragValue(dragVal);
  };
  return (
        <Child1 mouseDrag={dragHanlder} />
        <Child2 dragValue={dragValue}/>
  );
}

class Child2 extends React.Component {
   state = {
     afterCalculationsVal: 0
   };
   componentDidUpdate = () => {
      const { dragValue } = this.props;
      const someFinalval = val //this val takes dragValue applies checks, calculations and conditions and finally gives out some value
      this.setState({afterCalculationsVal: someFinalval });
   };

   render() {
      const { afterCalculationsVal } = this.state;
      return (
         <Child3 afterCalculationsVal={afterCalculationsVal} >
      );
   }
}

问题是我遇到了达到最大深度的问题,因为我正在设置连续的拖动状态。有什么办法可以克服这个问题。我不能直接在 Child2 中使用 'dragValue' 传入的道具,道具值的计算是强制性的,之后我必须设置状态。

切勿在 componentdupdate 中使用 this.setState 而不检查您更改的值是否确实已更改。事实上,这会触发无限循环

componentDidUpdate = () => {
      const { dragValue } = this.props;
      const someFinalval = val //this val takes dragValue applies checks, calculations and conditions and finally gives out some value
      if(/** your check *//)
      this.setState({afterCalculationsVal: someFinalval });
   };

问题是当组件更新时,它会进入 componentDidUpdate 然后设置状态导致另一个更新。设置 if 条件检查阻力值应该可以解决您的问题。

componentDidUpdate = (prevProps, prevState) => {
    const { dragValue } = this.props;
    if(prevState.dragValue !== prevState.dragValue){
      // Will only re-render when dragValue changes
      const someFinalval = val 
      this.setState({afterCalculationsVal: someFinalval });
    }
  };