在reactjs中渲染对象

时间:2017-05-23 15:25:58

标签: arrays json rest reactjs

我有symfony rest api,我正在为此写一些前端(第一次使用react)。所以,这是我的index.js:

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);

来自api的回复如下:

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

我如何迭代并将其打印到屏幕上? 现在我没有收到任何错误,只是收到服务器的回复,但屏幕上没有任何内容。

问候

1 个答案:

答案 0 :(得分:3)

它不是array,而object如此直接map将无效。首先,我们需要使用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:将返回array的所有密钥的object

检查工作代码段:

&#13;
&#13;
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);
&#13;
<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'/>
&#13;
&#13;
&#13;