重复更新状态-ReactJs

时间:2020-07-13 21:24:10

标签: javascript reactjs react-props

嗨,我有一个父组件,有两个子组件,如下所示,Child1具有可拖动的div元素,在拖动时会将其赋值给Parent组件,然后我必须将其传递给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中props中附带的'dragValue',props值的计算是强制性的,此后我必须设置状态。

2 个答案:

答案 0 :(得分:1)

在未检查您更改的值是否确实更改的情况下,切勿在componentdidupdate中使用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 });
   };

答案 1 :(得分:1)

问题在于,当组件更新时,它将进入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 });
    }
  };