reactjs - 使用 React 更新关于 props 变化的 C3 图表

标签 reactjs c3

我正在尝试美化作为 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;

最佳答案

根据the project's documentation :

By using APIs, you can update the chart after it's been rendered. ... APIs can be called through the object returned from 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);
    },

    // ...
});

然后,你想在 props 更新时更新图表; React 提供了一个名为 componentWillReceiveProps 的生命周期钩子(Hook),它在 props 更改时运行。

var ChartDailyRev = React.createClass({
    // ...

    componentWillReceiveProps: function (newProps) {
        this.chart.load({
            json: newProps.data
        }); // or whatever API you need
    }
});

(确保从 render 函数中删除 this._renderChart。)

关于reactjs - 使用 React 更新关于 props 变化的 C3 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018487/

相关文章:

javascript - react 状态没有改变

css - REACTJS - 3 个基于网格的大小为 16 的框 :9 , 显示图片失真

javascript - C3图表: Hiding Keys on Bar Graphs

javascript - C3.js 从按钮点击显示工具提示

javascript - 为什么 C3 图表没有出现?

javascript - 使用 Vanilla JavaScript 合并对象

javascript - 在Sinon 中,spyOn.and.callFake 相当于什么?

android - React-native: "could not connect to development server"- 安卓应用

c3js - 显示在内容顶部的网格线

javascript - 如何消除c3js折线图中的轴线溢出