2017-10-06 134 views
0

我想從「https://blockchain.info/api/exchange_rates_api」中獲取所有數據並在Page上顯示。我試過了,但收到了一條錯誤消息。這裏是我的代碼:如何獲取JSON API數據並在頁面上顯示使用react.js

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方法時,我在控制檯中獲取了數據。但我希望以表格形式在頁面上顯示數據。

+0

你說你得到裏面的setState一個錯誤,你可以顯示錯誤 – linasmnew

回答

0

問題是,你收到來自API調用JSON響應是對象沒有陣列。對象沒有定義map函數。首先,您需要將對象轉換爲數組。

+0

謝謝,先生,但仍然面臨問題 – tshr

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 
      }); 
     }) 
+0

謝謝你,夫人我已經設置了數據:[findresponse.data]但我在render()方法中遇到問題plz幫助我希望API數據以表格的形式進入頁面。 – tshr

+0

@tshr'findresponse'沒有'.data',它只是'findresponse'。渲染方法中的問題是什麼?表格格式是什麼意思?在一個HTML'

'? – Jalissa

+0

是的女士在HTML

tshr

相關問題