我是MERN的新手,我尝试使用axios显示mongodb集合中的数据。我尝试在网页上显示城市列表。我不确定我是否正在写。我应该使用超级状态吗?json postman
这是我的reactjs代码:
import React, { Component } from 'react';
import axios from 'axios';
export class Cities extends Component {
constaractor(state) {
state = {
locations:[]
};
}
componentDidMount() {
axios.get('/cities')
.then(cities => console.log(cities.data))
.catch(e => console.log(e))
}
render() {
const cities=this.state.locations.map(location => (
<div key={location._id}>
<h1>{location.city}</h1>
<p>{location.contry}</p>
<h1>Cities</h1>
</div>
));
return (
<div className="Cities">
{cities}
</div>
);
}
}
export default Cities
答案 0 :(得分:0)
从数据源获取数据后,您必须记住要设置状态。
import React, { Component } from 'react';
import axios from 'axios';
export class Cities extends Component {
constaractor(state) {
state = {
locations:[]
};
}
componentDidMount() {
axios.get('/cities')
.then(({ data}) => this.setState({ locations: data })) // <-- set state
.catch(e => console.log(e))
}
render() {
const cities=this.state.locations.map(location => (
<div key={location._id}>
<h1>{location.city}</h1>
<p>{location.country}</p> // <-- you had a typo here
<h1>Cities</h1>
</div>
));
return (
<div className="Cities">
{cities}
</div>
);
}
}
export default Cities