因此,我有一個運行Axios請求的React組件,結果設置爲我的'ist'狀態屬性,然後在渲染上進行檢查。React - Axios數據不會呈現一次獲取的數據
我的問題是,因爲它是一個異步請求,第一渲染檢查跑進return <p>Loading...</p>;
我正在尋找一種方式,我的組件以使負荷直到aync要求擁有完整,然後渲染結果。
這裏是我的代碼:
// 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;
任何幫助或建議表示讚賞 - 謝謝你提前。
dayumm,我的控制檯是非常誤導哈哈:) - 許多感謝 –