2017-10-10 143 views
0

這裏是我的代碼,我沒有得到如何在頁面上顯示數據。當我試圖給我的頁面上也沒有,它表明:如何獲取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.key}</span> 
       </div> 
      ) 
      } 
     </div> 
     ) 
    } 
} 

export default App; 
+1

findresponse是怎麼樣的?你需要括號嗎數據:[findresponse]'? – Walk

回答

0

這是一個反應警告。

由於每docs

「鑰匙」是一個特殊的字符串屬性,你需要的時候 創建元素的列表,包括。

您在訪問比特幣返回的數據時遇到問題,因爲您有一組對象。要訪問從API返回的數據,你需要做類似如下:

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

 
    componentDidMount() { 
 
    fetch("https://blockchain.info/ticker"). 
 
     then(response => response.json()). 
 
     then(findresponse => { 
 
     this.setState({ 
 
      data: [findresponse] 
 
     }); 
 
     }) 
 
    } 
 

 
    render() { 
 
    return (
 
     <div> 
 
     { 
 
      this.state.data.map((dynamicData, Key) => { 
 
      let keys = Object.keys(dynamicData); 
 
      let d = dynamicData; 
 
      return keys.map(data => { 
 
       return (
 
       <div style={{borderBottom: '1px solid black'}}> 
 
        <p>Currency: {data}</p> 
 
        <p>Buy: {dynamicData[data].buy}</p> 
 
       </div> 
 
      ); 
 
      }); 
 
      }) 
 
      
 
     } 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 

 

 
ReactDOM.render(<Example />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>

+0

在那個比特幣API中,我應該給什麼鑰匙 – tshr

+0

@tshr看到更新回答 –

+1

謝謝,這麼多先生 – tshr

0

有什麼用您的代碼錯誤的根本還是僅僅是一個關於warning消息問題?如果是這種情況,只要你在React中映射一個數組,你必須給它們一個key道具。這很有幫助,因此React知道哪些項目將來會更改,更新甚至添加。

// Key here stands for dynamicData's index in the array and not its key prop. 
this.state.data.map((dynamicData, Key) => 
    <div key={Key}> 
    <span>{dynamicData.key}</span> 
    </div> 
) 

我建議你把它從Keyindex重命名,這樣你就不是你的代碼中混淆密鑰。

this.state.data.map((dynamicData, index) => 
    <div key={index}> 
    <span>{dynamicData.key}</span> 
    </div> 
) 

更多有關keys的反應,我建議你閱讀this鏈接。

相關問題