2017-05-23 8 views
1

私はsymfonyの残りのAPIを持っています。私はこのためにフロントエンドを書くつもりです。だから、ここに私のindex.jsは次のとおりです。APIから残りのapiから配列を取得してレンダリングします。React

import React, {Component} from 'react'; 
import ReactDOM from 'react-dom'; 
import axios from 'axios'; 

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

    componentDidMount() { 
     const url = 'http://localhost/app.php/api/visits?from=2017-05-05&to=2017-05-08'; 
     axios.get(url) 
      .then(response => response.json()) 
      .then(
       visits => this.setState({visits}) 
      ).catch(err => err) 
    } 

    render() { 
     return (
      <div> 
       <ul> 
        {this.state.visits.map((visit, index) => <li key={index}>{visit}</li>)} 
       </ul> 
      </div> 
     ) 
    } 
} 
const app = document.getElementById('app'); 
ReactDOM.render(<App/>, app); 

応答は次のようになります。

{ 
    "2017-05-05": 2, 
    "2017-05-06": 8, 
    "2017-05-07": 10, 
    "2017-05-08": 1, 
} 

どのように私はそれを反復処理して画面に出力することができますか? 私は何のエラーもなく、ただサーバーからの応答を得ていますが、画面上には何も持っていません。

挨拶

答えて

3

そのない任意のarrayので、直接そのobjectmapは、その上で動作しません。まず、Object.keys()を使用してarrayのすべてのキーを取得し、それにmapを使用する必要があります。

render() { 
    let visits = this.state.visits; 
    return (
     <div> 
      <ul> 
       {Object.keys(visits).map((visit, index) => <li key={index}>{visit} : {visits[visit]}</li>)} 
      </ul> 
     </div> 
    ) 
} 

Object.keys:そのobjectのすべてのキーのarrayを返します。このよう

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

 
    componentDidMount() { 
 
     this.setState({ 
 
      visits: { 
 
       "2017-05-05":2, 
 
       "2017-05-06":8, 
 
       "2017-05-07":10, 
 
       "2017-05-08":1 
 
      } 
 
     })   
 
    } 
 

 
    render() { 
 
     let visits = this.state.visits; 
 
     return (
 
     <div> 
 
      <ul> 
 
       {Object.keys(visits).map((visit, index) => <li key={index}>{visit} : {visits[visit]}</li>)} 
 
      </ul> 
 
     </div> 
 
    ) 
 
    } 
 
} 
 
const app = document.getElementById('app'); 
 
ReactDOM.render(<App/>, app);
<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='app'/>

+0

うん、この配列についての私の悪い:

は作業スニペットを確認してください。私はリクエストでいくつかの変更を加えました(フェッチするためにAxiosが変更されました)、あなたのコードで動作しています、ありがとう! :) –

+1

また、 '[key、value]'のリストを返す 'Object.entries'を使うこともできます:' Object.entries(visits).map(([visit、n]、index)=>

  • {visit}:{n}
  • ) –

    +0

    @AndreaReinaはこの簡単な解決策に感謝しています:) –

    関連する問題