我正在使用 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
但我得到了同样的错误。我哪里做错了?谢谢!