我有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,
}
我如何迭代并将其打印到屏幕上? 现在我没有收到任何错误,只是收到服务器的回复,但屏幕上没有任何内容。
问候
答案 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
。
检查工作代码段:
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;