React render函数防止每次调用时创建新的canvas元素-Charts.js [英] React render function preventing creating new canvas element on each time invoked - Charts.js

查看:127
本文介绍了React render函数防止每次调用时创建新的canvas元素-Charts.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React,Charts.js和react-chart.js。

I am using React, Charts.js and react-chart.js.

我正在提出一个API请求,该请求返回的数据我正在可视化。我遇到的问题是,当页面最初加载时,它仅显示名称之一,然后再次呈现,并显示三个名称的完整列表。问题是每次调用render函数时都会创建一个新图形。

I am making an API request which returns data that i am then visualizing. The problem I am having is that when the page initially loads it only displays one of the names, an then it renders again and the complete list of three names is shown. The problem is that a new graph is created each time the render function is invoked.

有人知道是否有一种方法可以防止每次创建新图形时,

Does anyone know if there is a way to prevent a new graph being created each time, but instead to overwrite the previous graph that was created?

画布被渲染两次,我想这应该是代码设置的方式。在第一个画布元素上,它只有一个名称,但是在第二个画布上,它包含所有三个名称

The canvas is being rendered twice, which I guess is expected the way the code is setup. On the first canvas element it just has one name, but then on the second canvas it contains all three names

请在下面查看我的代码:

Please see my code below:

var App = React.createClass({
  getInitialState: function() {
    return {
      names: [],
      isLoaded: false
    }
  },
  componentDidMount: function() {
    $.get(url, function(data) {
      this.setState({
        names: data,
        isLoaded: true
      })
    }.bind(this));
  },
  render: function() {
    return ( < div > {
      this.state.isLoaded ? < Graph names = {
        this.state.names
      }
      /> : <div>Still Loading... </div >
    } < /div>)
  }
});

var Graph = React.createClass({

  render: function() {
    var names = [];
    for (var i = this.props.artists.length - 1; i >= 0; i--) {
      names.push(this.props.names[i].name);
    }

    var chartData = {
      labels: names,
      datasets: [{
        data: goals
      }, {
        data: predictions
      }]
    };

    return <LineChart data = {chartData} width = "600" height = "250" / >
  }
});


推荐答案

我认为问题不在React上,而在ChartJS ...它正在获取新信息...但是没有更新...而是插入新画布。.

I think the problem is not on React, but in ChartJS ... It's getting new information... but instead of updating ... it is inserting new canvas..

尝试设置 redraw

从文档 https://github.com/reactjs/react-chartjs


如果传递给组件的数据发生变化,点将使用chart.js的.update()在
值之间设置动画。如果您希望销毁图表并在每次更改时重新绘制
,则将重新绘制作为道具传递。例如
< LineChart data = {this.state.chartData}重绘/>

这篇关于React render函数防止每次调用时创建新的canvas元素-Charts.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆