So I have a React component which is running an Axios request, the result is set to my 'ist' state property and then checked on the render.
My problem is that because it is an async request, the first render check runs into the return <p>Loading...</p>;
I'm looking for a way for my component to render the Loading until the aync request has complete and then render the results.
Here is my code:
// defealts
import React from 'react';
import { Helmet } from 'react-helmet';
import axios from 'axios';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
pageName: 'Home',
list: '',
};
}
componentDidMount() {
this.test();
}
test = () => {
axios.get('https://api.myjson.com/bins/vqqml')
.then((response) => {
/* eslint-disable no-console */
console.log(response);
/* eslint-enable no-console */
this.setState({ list: response.data });
})
.catch((error) => {
/* eslint-disable no-console */
console.log(error);
/* eslint-enable no-console */
});
};
render() {
if (this.state.list.data) {
return (
<div>
<p>{this.state.list.data.name}</p>
</div>
);
}
return <p>Loading...</p>;
}
}
export default Home;
Any help or advice is appreciated - thank you in advance.
It doesn't render because this.state.list
does not have a data
property, it has name
, age
, and car
properties.
Your API call response is:
{"name":"John","age":30,"car":null}
and not
{"data":{"name":"John","age":30,"car":null}}
You could just create another property in state
called loaded
and set it to true
if you get a response. this.setState({ list: response.data, loaded: true });
And then ask in your render
:
if(this.state.loaded) {...}
You got to provide your response
in order to check if data
property is even in it. You might have confused the axios
response.data
with something else like @AndyGaskell already mentioned
You can try to use shouldComponentUpdate()
shouldComponentUpdate(){
if (nextState. list == this.state.list) {
return false;
}
}
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.