javascript - 错误:警告: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
但这也不起作用,而是引发了一些其他错误。任何帮助,将不胜感激。谢谢你!
解决方案
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)}
从您获得此值的任何地方,您都需要将其作为参数传递给该函数
推荐阅读
- ios - 在 iOS 应用程序中实现单个 Flutter 页面时打印到控制台?
- sql-server - 临时表与 CTE 的不同结果
- node.js - express-validator 没有在 express 4 中正确初始化
- flutter - 如何在 Dart 中将变量名转换为字符串?
- algorithm - 为什么我们需要在 Dijkstra 中按距离升序取边?
- javascript - 在需要相同值的组件中更新 Redux 状态的最佳实践是什么?
- validation - 条纹验证卡元素已填写
- node.js - 连接到 MongoDB Atlas 超时
- html - CSS 宽度/高度问题
- material-ui - 与 Formik 一起使用时如何在 Material UI 中禁用文本字段