【问题标题】:How to get data from JSON ReactJs如何从 JSON ReactJs 获取数据
【发布时间】:2020-04-29 20:55:03
【问题描述】:

我有一个这样的 JSON 数据: My JSON data

这是我的代码:

class WorldLineChart extends Component{
    constructor(props) {
        super(props);
    
        this.state = {
          data: []
        };
      }
    componentDidMount(){
        axios.get(`https://td.fpt.ai/corona/corona-total.json`)
        .then(res => {
            const data = res.data;
            console.log(data);
            this.setState({data: data});
        });
    }

    render(){

        const data = this.state
       
        return(
            <div>
               
            </div>
        )
    }

}
这是我运行上面的代码后得到的: Result

我想知道如何获取所有键和每个值(这是一个数组)来使用 ReactJs 绘制折线图。

这是我的折线图的代码:

const lineChart = (
        data
        ? (
            <Line
                data = {{
                    labels: //what i have to put in here,
                    datasets: [{
                        data: //what i have to put in here,
                        label: 'Infected',
                        borderColor: '#3333ff',
                        fill: true
                    }, {
                        data: //what i have to put in here,
                        label: 'Recovered',
                        borderColor: 'green',
                        backgroundColor: 'rgba(255,0,0,0.5)',
                        fill: true
                    },{
                        data: //what i have to put in here,
                        label: 'Deaths',
                        borderColor: 'red',
                        backgroundColor: 'rgba(0, 255, 0, 0.5)',
                        fill: true
                    }],
                }}
            /> ): null
    );

非常感谢!

【问题讨论】:

    标签: json reactjs chart.js


    【解决方案1】:

    你的数据可以使用this.state.data访问,你需要重构

    const data = this.state
    

    const {data} = this.state
    

    和说的一样

    const data = this.state.data
    

    【讨论】:

    • 欢迎@ChuẩnPhạm。乐意效劳。如果这解决了您的问题,请标记问题已解决。
    【解决方案2】:
    {
    Array.isArray(data) ?
    data.map((data,index) => <div key={index}>{data.bind your data}</div>) :  error
    }
    

    认为这应该会有所帮助。

    【讨论】:

    • 在用户的代码中数据是指状态,它不是一个数组,因此 data.length 会抛出错误。数组检查,推荐使用Array.isArray
    • @gautamits 是的,现在知道了,实际上 res.data 可以直接提供给 setState 中的数组,对吧。?
    • 是``` this.setState({data: res.data}); ``` 完全没问题。请更新您的代码,以免 OP 感到困惑。
    • @gautamits 是的,我已经发布了一个基于分页的问题(状态更新)你能看看那个,这会有所帮助。
    • 当然。请提供链接。
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2016-12-25
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2020-08-27
    相关资源
    最近更新 更多