基于api响应React渲染Chart.js [英] React render Chart.js based on api response

查看:45
本文介绍了基于api响应React渲染Chart.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用reacts和chart.js,以及chart-js / react包装器。我从API动态提取数据,然后将图表基于返回的数据。问题在于,图中仅显示了API调用中的一个名称。应该有三个名称。

I am using reacts and chart.js, and the chart-js/react wrapper. I am dynamically pulling the data from an API and then basing the chart on the data returned. The issue is that it is only one name from the API call that is being displayed in the graph. There should be three names.

我认为问题在于 Graph 组件的渲染之前API已返回所有数据,因此图形仅包含名字。至少这是我的想法。我曾尝试使用 componentWillMount 函数,但无法使其正常工作。

I think the problem is that the rendering of the Graph component is being rendered before all the data has been returned by the API, so the graph only contains the first name. At least this is what i think. I have tried working with the componentWillMount function but cannot get it working.

有人可以发现我的代码有问题吗?

can anyone spot anything wrong with my code below?

var App = React.createClass({

    getInitialState: function(){
        return {
            names: []
        }
    },

    componentDidMount: function() {
        $.get(url, function (data) {
            this.setState({ names: data })
        }.bind(this));
    },

    render: function() {
        return(
            <div>
                <Graph names={this.state.names}/>               
            </div>
        )
    }
});

var Graph = React.createClass({

    render: function() {
        for(var i = 0; i < this.props.names.length; 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"/>
    }
});


推荐答案

您必须像下面那样控制状态:

You have to control your state like 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>
        )
    }
});

因此,一旦获得所有数据,就可以呈现图表,否则显示加载屏幕。看看这个链接可能对您有帮助。希望对您有意义。

So once you get all your data you can render your chart otherwise show the loading screen. Take a look at this Link probably it will be helpfull for you. Hope it makes sense for you.

这篇关于基于api响应React渲染Chart.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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