How to Render State in Reactjs?
I Am a Backend Python Developer. but I Need to Make a Simple Front on the React. I Send a Request, I Get a Response, but I Can’t Get the State Out. Class...
I am a backend Python developer. But I need to make a simple front on the React. I send a request, I get a response, but I can’t get the state out.
class AppsList extends Component {
state = {
apps: []
}
componentDidMount() {
axios.get('/apps')
.then(function (response) {
console.log(response);
this.setState({
apps: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
aaa
<p>{this.state.apps}</p>
aaa
</div>
);
}
}
Response
3 Answers
Try to identify "this" out of the promise and map on this.state.apps like this:
class AppsList extends Component {
state = {
apps: []
}
componentDidMount() {
const {setState} = this;
axios.get('/apps')
.then(function (response) {
console.log(response);
setState({
apps: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
aaa
<div>
{this.state.apps.map((app) => {
return (<p key={app.id}>{app.name}</p>)
})}
</div>
aaa
</div>
);
}
}
The callback is not in arrow notation.
You can simply do:
.then(response => this.setState({ apps: response.data }))
You can do:
class AppsList extends Component {
state = {
apps: []
}
componentDidMount() {
axios.get('/apps')
.then(function (response) {
console.log(response);
this.setState({
apps: response.data
})
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
aaa
<p>{this.state.apps.map(elem => <div>{elem.id} {elem.name}</div>)}</p>
aaa
</div>
);
}
}