首页 > 解决方案 > 更新第三方对象的状态

问题描述

我是 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 没有做任何事情。如果我的任何做法是错误的,请纠正我。

标签: reactjsmxgraph

解决方案


这能解决您的问题吗?

更新您的构造函数:

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();
    }
    }));
}

推荐阅读