我试图在数据更改时美化作为React组件编写的C3图表的更新.数据通过其props从父组件流向组件.
我现在的解决方案"有效"但似乎不是最佳的:当新数据进入时,整个图表会重新生成.我想转换到新状态(行移动而不是整个图表更新闪烁).C3 API似乎有很多方法,但我找不到如何到达图表.
var React = require("react");
var c3 = require("c3");
var ChartDailyRev = React.createClass({
_renderChart: function (data) {
var chart = c3.generate({
bindto: '#chart1',
data: {
json: data,
keys: {
x: 'date',
value: ['requests', 'revenue']
},
type: 'spline',
types: { 'revenue': 'bar' },
axes: {
'requests': 'y',
'revenue': 'y2'
}
},
axis: {
x: { type: 'timeseries' },
y2: { show: true }
}
});
},
componentDidMount: function () {
this._renderChart(this.props.data);
},
render: function () {
this._renderChart(this.props.data);
return (
<div className="row" id="chart1"></div>
)
}
});
module.exports = ChartDailyRev;
Run Code Online (Sandbox Code Playgroud)
Mic*_*ley 11
根据项目的文件:
通过使用API,您可以在呈现图表后更新图表....可以通过返回的对象调用API
generate().
因此,您需要做的第一件事是在生成图表时保存对图表的引用.将它直接附加到组件很容易:
var ChartDailyRev = React.createClass({
_renderChart: function (data) {
// save reference to our chart to the instance
this.chart = c3.generate({
bindto: '#chart1',
// ...
});
},
componentDidMount: function () {
this._renderChart(this.props.data);
},
// ...
});
Run Code Online (Sandbox Code Playgroud)
然后,你想在道具更新时更新图表; React提供了一个生命周期钩子componentWillReceiveProps,在道具发生变化时运行.
var ChartDailyRev = React.createClass({
// ...
componentWillReceiveProps: function (newProps) {
this.chart.load({
json: newProps.data
}); // or whatever API you need
}
});
Run Code Online (Sandbox Code Playgroud)
(确保this._renderChart从您的render功能中删除.)
| 归档时间: |
|
| 查看次数: |
4097 次 |
| 最近记录: |