首页 > 解决方案 > 错误:警告:setState(...):在现有状态转换期间无法更新(例如在 `render` 或另一个组件的构造函数中)

问题描述

我有一个反应组件,它基本上是一个提交公司数据的表单。在我填写表格之前一切正常,但是当我提交表格并进入下一页时,它显示以下错误:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern but can be moved to `componentWillMount`.

我尝试在其他问题和 GitHub 中寻找答案,但无济于事。我对该组件的整个代码在这里:

https://gist.github.com/BikalNepal/b0185dee1528e396ff3a91a4f0caf9bd

我知道这可能会发生,因为 setState 是一个异步函数,所以我尝试将 await 放在前面,setStates但这也不起作用,而是引发了一些其他错误。任何帮助,将不胜感激。谢谢你!

标签: javascriptreactjsasynchronoussetstate

解决方案


 this.handleImageLoaded = this.handleImageLoaded.bind(this);
 this.handleOnCropComplete = this.handleOnCropComplete.bind(this);
 this.handleOnCropChange = this.handleOnCropChange.bind(this);

你的这个函数调用是错误的,你必须传递要触发的参数

    handleOnCropChange(crop) {
     this.setState({ crop });
    }

              <div>
                <ReactCrop
                  src={
                    this.state.companyImage === null
                      ? ""
                      : this.state.companyImage
                  }
                  crop={this.state.crop}
                  onImageLoaded={this.handleImageLoaded}
                  onComplete={this.handleOnCropComplete}
                  onChange={() => this.handleOnCropChange(this.state.crop)}
                  keepSelection={true}
                />
              </div>

例如像这样并检查其他功能

 handleOnCropComplete(crop, pixelCrop) {
   const companyImage = this.state;
   this.makeClientCrop(crop, pixelCrop);
  }
 onComplete={() =>this.handleOnCropComplete(crop,pixelCrop)}

从您获得此值的任何地方,您都需要将其作为参数传递给该函数


推荐阅读