我在 Redux 应用程序中使用的 React 组件中有一个 D3(v3) 图表。处理我的 D3 图表更新以反射(reflect)我的 Redux 存储更改的最佳方法是什么?
现在,我在 React 组件中有一个函数调用图表的绘制,还有一个函数在调用 componentWillUpdate
时立即调用删除之前的图表:
export default class Chart extends Component {
componentWillUpdate(nextProps) {
this.removePreviousChart();
this.drawChart(nextProps.chartData);
}
removePreviousChart(){
const chart = document.getElementById('chart');
while(chart.hasChildNodes())
chart.removeChild(chart.lastChild);
}
}
drawChart() {
//appends an svg to #chart html element and draws a d3 Chart
}
render(){
this.drawChart();
return(<div id='chart' />)
}
}
任何关于如何改进这个问题的替代方法、伪代码、想法或反馈都将不胜感激。
最佳答案
您采用的方法似乎很适合。
componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.
注意
componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false.
您可以从 here 阅读更多内容
如果你想在收到 newProps
时 setState()
使用 componentWillReceiveProps()
,它会为每个新 Prop 触发。
每次有新 Prop 时,使用您的Chart
API
进行绘制。
export default class Chart extends Component {
componentWillReceiveProps(nextProps) {
this.removePreviousChart();
this.drawChart(nextProps.chartData);
}
removePreviousChart(){
const chart = document.getElementById('chart');
while(chart.hasChildNodes())
chart.removeChild(chart.lastChild);
}
}
drawChart(chartData) {
const chart = document.getElementById('chart'); //fails if DOM not rendered
//appends an svg to #chart html element and draws a d3 Chart
//assuming you chart function as Chart(element, data);
if(chart && chartData){ //draw only if DOM rendered and have chartData
new Chart(chart, chartData); //calls to draw graph
}
}
render(){
return(<div id='chart' />)
}
}
关于reactjs - 在 React/Redux 中更新 D3 Chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731422/