2017-07-30 43 views
0

我需要幫助確定爲什麼地圖函數不能按預期工作。我在ComponentDidMount中放置了一個AJAX請求,我能夠在控制檯日誌中看到數據,但是我無法訪問它。我假設數據沒有被傳入setState()。React渲染:object.map()不是函數

import React from 'react'; 
import $ from 'jquery'; 


export default class Bitcoin extends React.Component{ 
constructor(props){ 
super(props); 
    this.state = { 
    prices:[] 
    } 
} 

componentDidMount(){ 
$.ajax({ 
    type: 'GET', 
    url: 'https://index.bitcoin.com/api/v0/lookup?time=2017-01-01T06:00:00Z', 
    dataType: 'json', 
    success: function(data) { 
    console.log(data) 
    this.setState({prices: data}); 
    }.bind(this), 
    error: function(xhr, status, err) { 
    console.error(this.props.url, status, err.toString()); 
    }.bind(this) 
}); 
} 

render(){ 
const { prices } = this.state; 
return(
    <div> 
    <p> 
     { 
     prices.map(function(price){ 
      return <p key={price.code}>{price.description}{price.rate}</p> 
     }) 
     } 
     </p> 
    </div> 
    ) 
    } 
} 

控制檯輸出 console

+1

對象沒有指定映射函數。一個數組可以。你的數據響應是一個對象,所以它輸出我沒有地圖功能。 –

回答

0

您的端點正在返回一個不是數組的對象。您可以使用UnderscoreJS提供的實用程序功能,該功能允許您映射對象。

另外,您應該考慮使用axios來製作您的AJAX請求,因爲它有助於保持您的bundle.js文件的輕量級。

0

查找端點沒有返回一個數組,它返回一個JSON對象,以「打開」,「關閉」和「查找」的屬性。你應該只在你的渲染參考這些:

render(){ 
const { prices } = this.state; 
return(
    <div> 
    <p> 
     <p key={prices.open.price}</p> 
     <p key={prices.close.price}</p> 
     <p key={prices.lookup.price}</p> 
    </p> 
    </div> 
) 
} 
} 

我也認爲使用jQuery的是有點沉重的反應。使用提取https://www.npmjs.com/package/isomorphic-fetch或請求https://www.npmjs.com/package/request庫更簡單,特別是如果您想考慮客戶端和服務器端呈現