2
有時,當我們調用api時,響應需要很長時間,所以我們更願意顯示加載圖像直到響應來臨。 在ajax請求中有開始和結束事件來顯示加載圖像,我想在axios中使用相同類型的東西。 我想爲全球的axios庫中的每個請求做出反應。 請爲此向我推薦一些東西。在每個api調用上顯示加載圖像,直到響應全局在axios庫中
有時,當我們調用api時,響應需要很長時間,所以我們更願意顯示加載圖像直到響應來臨。 在ajax請求中有開始和結束事件來顯示加載圖像,我想在axios中使用相同類型的東西。 我想爲全球的axios庫中的每個請求做出反應。 請爲此向我推薦一些東西。在每個api調用上顯示加載圖像,直到響應全局在axios庫中
import React, {Component} from 'react';
import axios from 'axios';
import loading from '../loading.gif' // relative path to image
class Home extends Component {
constructor() {
super()
this.state = {
time: null,
loading: true,
retJobs: []
}
this.getJobs();
}
getJobs() {
axios.get('http://example.com/getData.php')
.then(response => {
this.setState({retJobs: response.data});
console.log(response);
console.log(this.state.retJobs.results.length);
console.log(this.state.retJobs.results);
this.setState({
time: response.data.time,
loading: false
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
let content;
if (this.state.loading) {
content = <img src={loading} alt="loading"/>// or another graceful content
} else {
content = <p className="jobCount">Found {this.state.retJobs.results.length} Jobs</p>;
}
return (
<div>
<h4>Home</h4>
<div className="App-intro">
<div className="container">
<div className="row mainContent">
<div className=" row mainContent">
{content}
{this.state.retJobs.results && this.state.retJobs.results.map(function (item, idx) {
return <div key={idx} className="col-lg-12">
<div className="jobs">
<div className="row jobHeader">
<div className="col-lg-6">
<h1>{item.jobTitle}</h1>
</div>
<div className="col-lg-6">
<h3>{item.locationName}</h3>
</div>
</div>
<div className="row">
<div className="col-lg-2">
<h2>{item.employerName}</h2>
</div>
<div className="col-lg-10">
<p>{item.jobDescription}</p>
</div>
</div>
</div>
</div>
})}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Home;
林相當新的react.js,我一直在尋找相同的答案,發現從這裏 –
https://www.robinwieruch.de/learn-react-before-using-redux這樣的方式/?utm_content=buffer9d1e9&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer –
仍然在分析和解決這個問題,如果這是正確的做法,但暫時適用於我,希望這可以幫助 –