如何获取JSON API数据并使用react.js在页面上显示

时间:2017-10-06 12:11:11

标签: json reactjs api

我想从“https://blockchain.info/api/exchange_rates_api”获取所有数据并在页面上显示。我试了但是收到了一条错误信息。这是我的代码:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(){
    super();
      this.state = {
        data: []
        }
    }

    componentDidMount() 
    {
      fetch("https://blockchain.info/ticker").
        then((Response) => Response.json()).
          then ((findresponse)=>
            {
              console.log(findresponse)
              this.setState({
                data:findresponse
                  });
            }) 
    }

    render() 
    {
      return(
        <div>
          {
            this.state.data.map((dynamicData, Key) =>
              <div>
                <span>{dynamicData}</span>
              </div>
            )
          }
        </div>
        )
    }
}

export default App;

我在setState方法中遇到错误。当我尝试不使用setState方法编写时,我在控制台中获取了数据。但我希望以表格形式在页面上显示数据。

2 个答案:

答案 0 :(得分:0)

问题是,您从api调用收到的JSON响应是对象而非数组。对象没有定义map功能。首先,您需要将对象转换为数组。

答案 1 :(得分:0)

您正在从API调用中获取一个对象,但您需要一个数组才能使用map,因此您需要执行此操作:

fetch("https://blockchain.info/ticker").
   then((Response) => Response.json()).
     then ((findresponse)=>
        {
          this.setState({
            data: [findresponse] //wrap findresponse brackets to put the response in an array
           });
        })