0

我正在使用 React-image-crop 选择图像的感兴趣区域,但我需要首先从道具中读取预设的裁剪尺寸,以便在图像打开时选择裁剪区域。我正在使用 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但我得到了同样的错误。我哪里做错了?谢谢!

4

2 回答 2

1

您的Image组件工作正常,没有任何错误: 实时查看 (正如您在日志中看到的,更新的数量是有限的。所以它没有您提到的问题。)

所以问题可能出在它的父组件上,或者在 redux 配置上,或者在另一个地方。

超过最大更新深度。

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

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

于 2020-08-06T10:34:49.737 回答
0

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

<ReactCrop src={this.state.imageURL} crop={this.state.crop} onChange={this.updateCrop} keepSelection />
于 2020-08-05T23:35:27.757 回答