在React/Redux中更新D3图表
问题描述:
在Redux应用程序中使用的React组件内有一个D3(v3)图表。处理我的D3图表更新以反映我的Redux商店更改的最佳方式是什么?在React/Redux中更新D3图表
现在,我有一个调用图表的绘制和调用只要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()。在更新发生之前使用此作为 执行准备的机会。对于初始渲染,此方法不称为 。
请注意,您不能在这里调用this.setState()。如果您需要更新 状态以响应支柱更改,请改为使用componentWillReceiveProps() 。
注
componentWillUpdate()将不会被调用,如果shouldComponentUpdate() 返回false。
如果你想setState()
在收到newProps
使用componentWillReceiveProps()
这是每一个新的道具解雇你可以阅读更多从here
。
使用你的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' />)
}
}
只有在接收到新的道具和/或状态时才会触发'componentWillUpdate'?我不确定在它上面使用'componentWillReceiveProps'的好处是什么。你能澄清吗? – Matt16749
@ Matt16749更新了我的答案。检查一次 –