最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react-chartjs-2 not updating graph when state updates - Stack Overflow

programmeradmin5浏览0评论

I am creating a dashboard app that fetches data from an endpoint and uses the setState method to assign variables from the JSON returned by the endpoint to state variables. When I make a change to state, some components like 'react-svg-gauge' will update but 'react-chartjs-2' does not update.

The below code is an example of how my state changes in my actual app. This example will display the correct value of the state variables in the chrome developer console but does not update the DOM accordingly.

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class DoughnutExample extends Component {
  state = {
    data: {
        labels: [
            'Red',
            'Green',
            'Yellow'
        ],
        datasets: [{
            data: [300, 50, 100],
            backgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ],
            hoverBackgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ]
        }]
    }
  }

  componentDidMount() {
    this.timer = setInterval(
      () => this.increment(),
      1000
    )
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  increment() {
    let datacopy = Object.assign({}, this.state.data)
    datacopy.datasets[0].data[0] = datacopy.datasets[0].data[0] + 10
    console.log(datacopy.datasets[0].data[0])
    this.setState({data: datacopy})
  }

  render(){
    return(
      <div>
      <Doughnut data = {this.state.data}/>
      </div>
    )
  }
}

export default DoughnutExample;

Am I using the lifecycle methods correctly? This code will update the value of the pie chart, the state variable but will not correctly render the DOM.

I am creating a dashboard app that fetches data from an endpoint and uses the setState method to assign variables from the JSON returned by the endpoint to state variables. When I make a change to state, some components like 'react-svg-gauge' will update but 'react-chartjs-2' does not update.

The below code is an example of how my state changes in my actual app. This example will display the correct value of the state variables in the chrome developer console but does not update the DOM accordingly.

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class DoughnutExample extends Component {
  state = {
    data: {
        labels: [
            'Red',
            'Green',
            'Yellow'
        ],
        datasets: [{
            data: [300, 50, 100],
            backgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ],
            hoverBackgroundColor: [
            '#FF6384',
            '#36A2EB',
            '#FFCE56'
            ]
        }]
    }
  }

  componentDidMount() {
    this.timer = setInterval(
      () => this.increment(),
      1000
    )
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

  increment() {
    let datacopy = Object.assign({}, this.state.data)
    datacopy.datasets[0].data[0] = datacopy.datasets[0].data[0] + 10
    console.log(datacopy.datasets[0].data[0])
    this.setState({data: datacopy})
  }

  render(){
    return(
      <div>
      <Doughnut data = {this.state.data}/>
      </div>
    )
  }
}

export default DoughnutExample;

Am I using the lifecycle methods correctly? This code will update the value of the pie chart, the state variable but will not correctly render the DOM.

Share Improve this question asked Mar 16, 2018 at 9:14 Bryan LicataBryan Licata 1831 gold badge1 silver badge7 bronze badges 1
  • I think you have to bind "this" to the increment function. – Janick Fischer Commented Mar 16, 2018 at 9:37
Add a comment  | 

3 Answers 3

Reset to default 12

The potential issue I see is that you try to update nested property while you mutate it. So if Doughnut is passing parts of data to other components they will not be notified that props have changed. So it is necessary to do deep clone:

increment() {
    const datasetsCopy = this.state.data.datasets.slice(0);
    const dataCopy = datasetsCopy[0].data.slice(0);
    dataCopy[0] = dataCopy[0] + 10;
    datasetsCopy[0].data = dataCopy;

    this.setState({
        data: Object.assign({}, this.state.data, {
            datasets: datasetsCopy
        })
    });
}

You may also need to bind the function like @Janick Fisher suggests.

Check this link. You can see that he binds the function to the component.

https://codepen.io/gaearon/pen/xEmzGg?editors=0010

// This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);

you can also empty the state variable and populate it again like

                this.setState({
                    mainData: {}
                });
                this.setState({
                    mainData: md
                });

while md been initialized with the value of mainData

发布评论

评论列表(0)

  1. 暂无评论