Reactjs 超出最大更新深度错误,反应图像裁剪

Reactjs 超出最大更新深度错误,反应图像裁剪,reactjs,react-image-crop,Reactjs,React Image Crop,我使用React image crop来选择图像的感兴趣区域,但首先我需要从道具中读取预设的裁剪尺寸,以便在图像打开时选择裁剪区域。我正在使用componentDidMount()更新处于状态的裁剪。但它不工作,我得到一个错误:超过了最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。 class Image extends Component<Ima

我使用React image crop来选择图像的感兴趣区域,但首先我需要从道具中读取预设的裁剪尺寸,以便在图像打开时选择裁剪区域。我正在使用componentDidMount()更新处于状态的裁剪。但它不工作,我得到一个错误:
超过了最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。

class Image extends Component<ImagePropsType, ImageStateType>{
  constructor(props: ImagePropsType) {
  super(props);
    this.state = {
      crop: { unit: 'px', y: 0, x: 0, width: 0, height: 0 },
      ...
    }
  }

  componentDidMount() {
    this.setState({
        crop: props.props.presetCrop  // { unit: 'px', y: 10, x: 30, width: 50, height: 90 }
    })
  }
  
  updateCrop = (crop: { unit: string, x: number, y: number, width: number, height: number }) => {
    this.setState({ crop: crop })
  }
  ...
  render() {
    return (
       <ReactCrop src={this.state.imageURL} crop={this.state.crop} onChange={(newCrop) => this.updateCrop(newCrop)} keepSelection />
    )
  }

}
类图像扩展组件{
构造函数(道具:ImagePropsType){
超级(道具);
此.state={
裁剪:{单位:'px',y:0,x:0,宽度:0,高度:0},
...
}
}
componentDidMount(){
这是我的国家({
裁剪:props.props.presetCrop/{单位:'px',y:10,x:30,宽度:50,高度:90}
})
}
updateCrop=(裁剪:{unit:string,x:number,y:number,width:number,height:number})=>{
this.setState({crop:crop})
}
...
render(){
返回(
this.updateCrop(newCrop)}keepSelection/>
)
}
}

我还尝试使用
getDerivedStateFromProps
更新处于状态的作物,但遇到了相同的错误。我哪里做错了?谢谢大家!

一旦您调用了
this.state.updateCrop
您应该调用
this.updateCrop

<ReactCrop src={this.state.imageURL} crop={this.state.crop} onChange={this.updateCrop} keepSelection />

您的
图像
组件工作正常,没有任何错误: (正如您在日志中看到的,更新的数量是有限的,因此没有您提到的问题。)

因此,问题可能在它的父组件上,或者在redux配置中,或者在其他地方

超过最大更新深度

在每次更新时设置状态时会发生这种情况。例如,使用此处理程序:
onChange={this.updateCrop(newCrop)}
而不是:
onChange={newCrop=>this.updateCrop(newCrop)}


(第一个在每次渲染时调用onChange,onChange将导致一个新的渲染,因此它将成为一个无限循环。)

您有什么可以在
componentWillUpdate
componentdiddupdate
生命周期方法中向我们展示的吗?我可以看到有
代表代码的其余部分?@antonioredeljac不,我没有componentWillUpdate或componentdiddupdate,我应该用它们代替componentDidMount吗?你确定你没有
onChange={this.updateCrop(newCrop)}
在您的原始代码中?@pangpp我根据您的新编辑更新了答案。很抱歉,在复制代码时出错,现在已编辑谢谢@yaya,实时代码非常有用,我将在您的帮助下检查其他组件suggested@pangppNp,happy coding:)我正在使用react image crop 8.6.2,并将其更新为8.6.4(正如您在实时代码中使用的那样)解决了这个问题。再次感谢@庞普Np,快乐编码:)