[英]Error when using setState inside a ReactJS API
我正在使用一个名为“react-svg”的 API,它允许我将 SVG 文件注入 DOM,并且还拥有 ZCD15A7Z5C26008696647B31A3F0DE43B3 元素的副本,以便稍后使用它。
This API has a functionality called 'afterInjection', it's basically a function called after injecting the SVG file, inside that function I tried to update the component state and I got an error:
错误:超过最大更新深度。 当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
import { ReactSVG } from 'react-svg';
import Sketch from '../sketch/Sketch';
import './ImageUploader.scss';
import Complex from 'complex.js';
class ImageUploader extends Component {
constructor( props ) {
super( props );
this.state = {
pointsArray : [],
fileURL : null,
file: null
}
this.handleChange = this.handleChange.bind(this);
}
handleChange = (event) => {
this.setState({
file : event.target.files[0],
fileURL: URL.createObjectURL(event.target.files[0])
})
}
add_svg = () => {
if (this.state.fileURL !== null) {
return (
<ReactSVG
src={this.state.file.name}
afterInjection={(error, svg) => {
if (error) {
console.error(error)
return
}
this.convert_path( svg.children[0].children[0] );
}}
/>
);
}
return null;
}
convert_path = path => {
let points = [];
const length = path.getTotalLength();
const step = length / 100;
for (let i = length - 1; i >= 0; i -= step) {
// console.log(path.getPointAtLength(i));
points.push( new Complex( path.getPointAtLength(i).x, path.getPointAtLength(i).y) );
}
this.setState({ pointsArray : points });
}
render() {
return (
<div >
<div className="upload_sketch_container">
<div className="input_container">
<input type="file" id="file" onChange={this.handleChange} />
<label htmlFor="file">Upload SVG file</label>
</div>
<div className="image_sketch_container">
<div className="image_container" >
{this.add_svg()}
</div>
<div className="sketch_container">
<Sketch data={this.state.pointsArray} />
</div>
</div>
</div>
</div>
);
}
}
export default ImageUploader;
您发布的错误消息完全正确。 您已经在组件中创建了一个无限循环。 您渲染组件,调用add_svg
,调用convert_path
,更新 state,触发重新渲染,调用add_svg
等。如果您在add_svg
中取消对this.convert_path
的调用,您的无限循环问题将消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.