简体   繁体   English

如何在反应中更新我的 chart.js 数据?

[英]How do I update My chart.js data in react?

I'm new to React, and I'm trying to figure out how to setState to the object, but it doesn't work when I this.setState({ datasets[0].data: }), in the function what do I need to do here??我是 React 的新手,我正在尝试弄清楚如何将 setState 设置为 object,但是当我在 function 中的 this.setState({ datasets[0].data: }) 时它不起作用我需要在这里做吗??

state={
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
        data: [0, 10, 5, 2, 20, 30, 45],
        label: "My First dataset",
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        }]
    }

    change = () => {
        this.setState({
            datasets: 
        })
    }
this.setState((prevState) => {
      const datasets = prevState.datasets;
      datasets[0].label = newLabel; //you can change particular value this way
      return {datasets};
});

What this does is actually make a copy of prevState datasets array of objects and the mutates its value as per the requirement.这实际上是复制 prevState datasets 对象数组,并根据要求改变其值。 Once the changes are done, we will setState value with the value of the updated datasets.更改完成后,我们将 setState 值与更新数据集的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM