chart.js load totally new data

前端 未结 20 1448
有刺的猬
有刺的猬 2020-11-28 21:12

The API for chart.js allows one to edit points of the datasets loaded into it, for example:

.update( )

Calling update() on

20条回答
  •  盖世英雄少女心
    2020-11-28 21:46

    If anyone is looking for how to do this in React. For a linechart, assuming you have a wrapper component around the chart:

    (This assumes you are using v2. You do not need to use react-chartjs. This is using the normal chart.js package from npm.)

    propTypes: {
      data: React.PropTypes.shape({
        datasets: React.PropTypes.arrayOf(
          React.PropTypes.shape({
    
          })
        ),
        labels: React.PropTypes.array.isRequired
      }).isRequired
    },
    componentDidMount () {
      let chartCanvas = this.refs.chart;
    
      let myChart = new Chart(chartCanvas, {
        type: 'line',
        data: this.props.data,
        options: {
          ...
        }
      });
    
      this.setState({chart: myChart});
    },
    componentDidUpdate () {
        let chart = this.state.chart;
        let data = this.props.data;
    
        data.datasets.forEach((dataset, i) => chart.data.datasets[i].data = dataset.data);
    
        chart.data.labels = data.labels;
        chart.update();
    },
    render () {
      return (
        
      );
    }
    

    The componentDidUpdate functionality allows you to update, add, or remove any data from the this.props.data.

提交回复
热议问题