reactjs - 更新第三方对象的状态
问题描述
我是 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 没有做任何事情。如果我的任何做法是错误的,请纠正我。
解决方案
这能解决您的问题吗?
更新您的构造函数:
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();
}
}));
}
推荐阅读
- vim - VIM 大写自动补全
- android - 有没有一种方法可以知道我应该向用户请求哪些权限才能让 Google Play 接受我的应用程序?
- python - 在多个文件上应用 luigi 管道
- django-rest-framework - 从 Django Rest Framework 导入 format_suffix_patterns 时出错
- mysql - Sequelize:如何检查表中是否存在子字符串
- reactjs - 如何通过 `styled()` 使用 `as` 包装反应组件
- javascript - 网站 html/js 存储在本地计算机、chrome、windows 10 的什么位置?
- c# - 带有 Linq 表达式的 EF Core SQL 函数 LIKE 方法不适用于非字符串类型
- c - 返回一个大变量与使用参数中提供的指针设置它
- apache - Apache - 配置数百个类似站点,无需指定每个站点