简体   繁体   English

如何使用动态数据更新 Chartjs 图表 (react-chartjs-2)?

[英]How to update Chartjs chart (react-chartjs-2) with dynamic data?

I've been trying to make a simple chart generator in React.我一直在尝试在 React 中制作一个简单的图表生成器。 I use Handsontable to let the user enter dynamic data and I would like the changes to be reflected in the chart.我使用 Handsontable 让用户输入动态数据,我希望更改能够反映在图表中。 Here is my code: Codesandbox reproducible .这是我的代码: Codesandbox 可重现

Small disclaimer : the handsontable package is pretty buggy in codesandbox.小免责声明:掌上电脑 package 在 codesandbox 中有很多问题。 Just double click a number and an inputfield will appear where you can edit data.只需双击一个数字,就会出现一个输入字段,您可以在其中编辑数据。

The problem问题

For some reason, you can only edit something from the first data row and the second data row (labels not included).出于某种原因,您只能编辑第一个数据行和第二个数据行中的内容(不包括标签)。 After that, the chart won't update anymore.之后,图表将不再更新。 So try changing 11 under the Mercedes label and you will see what I mean.因此,尝试在Mercedes label 下更改11 ,您就会明白我的意思。 Those can be changed and the changes will be reflected in the chart, but any number changed after that won't update the chart.这些可以更改,更改将反映在图表中,但之后更改的任何数字都不会更新图表。

Now I've read this github issue where people suggest to add a random key ( key={Math.random()} ) or the redraw prop, and that somewhat works, but the whole chart gets redrawn, which is not exactly what I want.现在我已经阅读了这个github 问题,其中人们建议添加一个随机键( key={Math.random()} )或redraw道具,这有点管用,但整个图表都被重绘了,这不是我想要的想。

The problem was with mutating deep nested properties.问题在于改变深层嵌套属性。 I've used lodash clonedeep to deepclone the object. Then changing the contents of that object and setting the state. It all worked fine after that.我使用lodash clonedeep 深度克隆 object。然后更改 object 的内容并设置 state。之后一切正常。

I updated the codesandbox reproduction in case someone needs it.我更新了codesandbox 复制,以防有人需要它。

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

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