目录

Graph Data Structure

目录

Graph 数据结构,支持更新React组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
interface GraphObserver {
  onGraphDataChanged(graph: Graph): void;
}

class Graph {
  private observers: GraphObserver[] = [];

  // ...

  addObserver(observer: GraphObserver) {
    this.observers.push(observer);
  }

  removeObserver(observer: GraphObserver) {
    const index = this.observers.indexOf(observer);
    if (index !== -1) {
      this.observers.splice(index, 1);
    }
  }

  private notifyObservers() {
    for (const observer of this.observers) {
      observer.onGraphDataChanged(this);
    }
  }
}

class MyReactComponent extends React.Component implements GraphObserver {
  constructor(props: any) {
    super(props);
    this.state = { graph: new Graph([]) };
  }

  componentDidMount() {
    this.state.graph.addObserver(this);
    this.state.graph.load();
  }

  componentWillUnmount() {
    this.state.graph.removeObserver(this);
  }

  onGraphDataChanged(graph: Graph) {
    this.setState({ graph });
  }

  render() {
    // Render the graph nodes and edges using this.state.graph
  }
}