我正在用React构建一个可折叠的OrgChart
组件。
我不确定基于用户交互,如何使用生命周期方法重新渲染Edge(链接2个节点的SVG路径)。我想知道在这种情况下是否有比使用componentWillReceiveProps
更好的方法(或者因为它很快就会过时了,所以componentDidUpdate
和/或getDerivedStateFromProps
会被淘汰)
仅在首先绘制所有节点后才绘制边缘。但是在我的代码中,每个Node
都绘制其传入的Edge。这是因为使用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.tsx
:绘制SVG Edge 到目前为止,我正在考虑以这种方式组织代码:
Chart.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})
}
}
答案 0 :(得分:1)
我将使用一个简单的memoization approach:
calculateCoordinates = memoize((nodesLength, graph) => { your recalculation code })
render() {
const augmentedGraph = this.augmentGraph(this.props.graph.nodes.length, this.props.graph);
return {buildChart(rootNode, augmentedGraph)};
}
很显然,您的问题中缺少很多细节。例如,我缺少augmentedGraph
和rootNode
之间的连接。
通常,记忆化方法用于从组件(在这种情况下为扩充图)中删除状态。
传递给memoize
的lambda的参数是您要确定输入数据是否已更改并且需要重新执行计算代码的键。