【发布时间】: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 更新状态下的作物,但我得到了同样的错误。我哪里做错了?谢谢!
【问题讨论】:
-
您有什么可以在
componentWillUpdate或componentDidUpdate生命周期方法中向我们展示的内容吗?我可以看到有...代表其余代码? -
@AntonioErdeljac 不,我没有 componentWillUpdate 或 componentDidUpdate,我应该使用它们来代替 componentDidMount 吗?
-
您确定您的原始代码中没有
onChange={this.updateCrop(newCrop)}吗? -
@pangpp 我根据您的新编辑更新了答案。