我是React的初学者,我可能会做错所有这些事情,但是如何更新具有自己功能/变量的第三方对象的状态?
这是我的代码:
import React, { Component } from 'react';
import { mxGraph, mxRubberband, mxCell, mxGeometry, mxGraphHandler, mxEdgeHandler, mxParallelEdgeLayout, mxLayoutManager } from 'mxgraph-js';
class Graph extends Component {
constructor(props) {
super(props);
this.state = {graph: new mxGraph(this.refs.graph)};
}
shouldComponentUpdate() {
return false;
}
componentDidMount() {
let graph = this.state.graph;
new mxRubberband(graph);
let parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try {
let v1 = graph.insertVertex(parent, null, 'Hello world!', 20, 20, 80, 30);
} finally {
graph.getModel().endUpdate();
}
this.setState({graph});
}
render() {
return <div ref="graph" className="graph"/>
}
}
export default Graph;
图形加载到屏幕上,但是graph.insertVertex不执行任何操作。如果我的任何做法有误,请纠正我。
答案 0 :(得分:0)
这可以解决您的问题吗?
更新您的构造函数:
constructor(props) {
super(props); // You don't need to do any work here
}
删除此内容,因为无需覆盖组件更新行为:
shouldComponentUpdate() {
return false;
}
更新您的componentDidMount
方法:
componentDidMount() {
this.setState({ graph: new mxGraph(this.refs.graph) }, () => {
// This callback is invoked after the state has been set. It is now safe to access the graph field on state.
let graph = this.state.graph;
new mxRubberband(graph);
let parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try {
let v1 = graph.insertVertex(parent, null, 'Hello world!', 20, 20, 80, 30);
} finally {
graph.getModel().endUpdate();
}
}));
}