簡體   English   中英

反應生命周期方法,是否為 componentWillReceiveProps

[英]React lifecyle methods, to componentWillReceiveProps or not

我正在用 React 構建一個可折疊的OrgChart組件。

我不確定如何根據用戶交互使用生命周期方法重新渲染邊緣(鏈接 2 個節點的 SVG 路徑)。 對於這種情況,我想知道是否有比使用componentWillReceiveProps更好的方法(或者因為它很快就會過時,改用componentDidUpdate和/或getDerivedStateFromProps

只有先繪制所有節點后,才應繪制邊。 但是在我的代碼中,每個Node繪制其傳入的邊緣。 這是因為使用CSS使圖表可折疊的 HTML 代碼需要Node及其Edge位於同一div

NodeContainer = (props) => 
  <div className='nodeContainer'>
    <Node />
    <Edge />
  </div>

我的OrgChart組件有 3 個主要組件:

  • Chart.tsx :接收包含節點和邊列表的graph對象道具,並使用它來構建圖表。 還接收一些其他道具,例如圖表或節點操作的回調函數(例如: onNodeSelected(id) , onChartMoved()
  • Node.tsx :繪制節點及其傳入的 svg Edge。
  • Edge.tsx : 繪制 SVG 邊緣

到目前為止,我正在考慮以這種方式組織我的代碼:

圖表.tsx

// augmentedGraph will have extra data for each node and edge.
// For example: the node coordinates, isCollapsed. The coordinates are purely a UI concern, hence why my incoming graph props should not contain the info.
class Chart extends Component {
  state = { augmentedGraph: this.props.graph }

  componentDidUpdate(prevProps, prevState) {

    if (this.props.graph.nodes.length !== prevProps.graph.nodes.length 
      || this.state.augmentedGraph !== prevState.augmentedGraph){

      // clone this.props.graph into this.state.augmentedGraph
      // and re-calculates all edges and nodes coordinates to add those properties to this.state.augmentedGraph
      ...

    }
  }

  // Will send callback function props to each Node (onNodeMoved, etc.), that will fire below method
  userModifiedChartHandler() {
    // re-calculates all edges and nodes coordinates and updates this.state.augmentedGraph
  }

  // recursively builds the chart html structure with Nodes and Edges.
  buildChart(node) {
    return ...
  }

  render() {
    const rootNode = this.state.augmentedGraph.nodes.root
    const chart = buildChart(rootNode)
    return ({chart})
  }
}

我會使用一個簡單的記憶方法

calculateCoordinates = memoize((nodesLength, graph) => { your recalculation code })

render() {
    const augmentedGraph = this.augmentGraph(this.props.graph.nodes.length, this.props.graph);
    return {buildChart(rootNode, augmentedGraph)};
}

顯然,您的問題中缺少很多細節。 例如,我缺少augmentedGraphrootNode之間的連接。
通常,記憶方法用於從組件中刪除狀態,在這種情況下,是增強圖。
傳遞給memoize的 lambda 參數是您要決定輸入數據是否已更改以及需要重新執行計算代碼的鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM