React render Chart.js based on api response

半城伤御伤魂 提交于 2020-01-23 17:14:08

问题


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.

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"/>
    }
});

回答1:


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.



来源:https://stackoverflow.com/questions/40722067/react-render-chart-js-based-on-api-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!