I am new to MERN and I try to display data from mongodb collection using axios. I try to display a list of cities on the web page. I am not sure if I am doing it write. Should I use super state?json postman
Here is my reactjs code:
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
You have to remember to set the state once you get data back from your data source.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.