【问题标题】:Maximum update depth exceeded error, React-image-crop最大更新深度超出错误,React-image-crop
【发布时间】:2020-11-26 04:04:46
【问题描述】:

我正在使用 React-image-crop 选择图像的感兴趣区域,但我需要首先从 props 中读取预设的裁剪尺寸,以便在图像打开时选择裁剪区域。我正在使用 componentDidMount() 来更新作物状态。但它不起作用,我收到一个错误:Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

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

}

我也尝试使用getDerivedStateFromProps 更新状态下的作物,但我得到了同样的错误。我哪里做错了?谢谢!

【问题讨论】:

  • 您有什么可以在componentWillUpdatecomponentDidUpdate 生命周期方法中向我们展示的内容吗?我可以看到有 ... 代表其余代码?
  • @AntonioErdeljac 不,我没有 componentWillUpdate 或 componentDidUpdate,我应该使用它们来代替 componentDidMount 吗?
  • 您确定您的原始代码中没有onChange={this.updateCrop(newCrop)} 吗?
  • @pangpp 我根据您的新编辑更新了答案。

标签: reactjs react-image-crop


【解决方案1】:

您的Image 组件工作正常,没有任何错误: see it live (从日志中可以看到,更新的数量是有限的。所以它没有你提到的问题。)

所以问题可能出在它的父组件上,或者使用 redux 配置,或者在其他地方。

已超过最大更新深度。

当您为每次更新设置状态时,就会发生这种情况。例如通过使用这个处理程序:onChange={this.updateCrop(newCrop)} 而不是:onChange={newCrop =&gt; this.updateCrop(newCrop)}

(第一个在每次render时调用onChange,onChange会导致新的render,所以会变成死循环。)

【讨论】:

  • 谢谢@yaya,实时代码很有帮助,我会按照你的建议检查其他组件
  • @pangpp Np,快乐编码:)
  • 我使用的是 react-image-crop 8.6.2,并将其更新到 8.6.4(正如您在实时代码中使用的那样)解决了这个问题。再次感谢!
  • @pangpp Np,快乐编码:)
【解决方案2】:

onChange 你打电话给this.state.updateCrop 你应该打电话给this.updateCrop

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

【讨论】:

  • 对不起,复制代码时出错,现在编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2021-08-31
  • 2020-12-17
  • 2019-09-22
  • 2020-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多