2017-10-10 16 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'はどのように見えますか?ここに角括弧が必要ですか?data:[findresponse] '? – Walk

答えて

0

これは反応の警告です。

docsあたりのとおり:「キーは」特別な文字列である

あなたは は、要素のリストを作成するときに含める必要が属性。

オブジェクトの配列があるので、bitcoinから返されるデータにアクセスする際に問題が発生しています。

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

そのbitcoin APIでは、どのような鍵を与えるべきですか – tshr

+0

@tshr更新された回答を参照してください –

+1

ありがとう、あまりにも先生 – tshr

0

はあなたのコードと全く何も悪いことありますか、それはwarningメッセージについてだけ質問です:あなたは、次のような何かをする必要がAPIから返されるデータにアクセスするには?その場合、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> 
) 

私はあなたがindexKeyから名前を変更することをお勧めので、あなたのコード内のキーを混同しないでください。リアクトでkeysの詳細については

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

、私はあなたがthisリンクを読むことをお勧めします。

関連する問題