[英]Display loader icon while data is loading
我正在尝试在加载数据时显示加载程序图标。 但是由于某些原因,当我尝试从API检索数据时,无法显示此加载程序图标。
我有这样的文件夹结构:
我的Cards.js中有以下代码
constructor(props) {
super(props);
this.state = this.state = {
posts: [],
loading: false
}
}
componentWillMount() {
this.loadData();
}
render() {
let data;
if(this.state.loading) {
data = <img data-src={ require('../images/loader.gif') } />
} else {
let records = this.fetchResult();
console.log(records);
return (
<div className='row'>
{ records }
</div>
)
}
}
// ==================================================================
loadData() {
const path = `${url}/jira_jobs.php`;
axios.get(path)
.then(res => {
this.setState({
posts: res['data'],
loading: false
});
})
.catch(err => {
console.error(err);
});
}
fetchResult() {
let records = this.state.posts.map((post) => (
<div key = { post.id }>
<h3>{ post.title }</h3>
<p>{ post.body }</p>
</div>
));
return records;
}
您没有在任何地方将loading
设置为true
。 尝试在loadData()
方法的开头将loading设置为true:
loadData() {
this.setState({loading: true});
const path = `${url}/jira_jobs.php`;
axios.get(path)
.then(res => {
this.setState({
posts: res['data'],
loading: false
});
})
.catch(err => {
console.error(err);
});
}
由于您正在使用的Promise的异步性质,因此可以使用此方法。
您不会在任何地方将loading属性设置为true。 您应该在loadData函数的开头将其设置为true,如下所示:
loadData() {
this.setState({
loading: true
});
const path = `${url}/jira_jobs.php`;
axios.get(path)
.then(res => {
this.setState({
posts: res['data'],
loading: false
});
})
.catch(err => {
console.error(err);
});
}
同样在您的render方法中执行此操作:
render() {
if(this.state.loading) {
return <img data-src={ require('../images/loader.gif') } />;
} else {
let records = this.fetchResult();
console.log(records);
return (
<div className='row'>
{ records }
</div>
)
}
}
您不要在loadData
中将loading设置为true
,也不要从render返回加载器,也不要忘记在发生错误时将loading
设置为false
。
loadData() {
this.setState({ loading: true });
const path = `${url}/jira_jobs.php`;
axios.get(path)
.then(res => {
this.setState({
posts: res['data'],
loading: false
});
})
.catch(err => {
this.setState({ loading: false });
console.error(err);
});
}
与三元运算符?
您可以使用更好的语法添加加载程序, if else
而且图像源应该是src
而不是data-src
render() {
return (
<div className='row'>
{this.state.loading
? <img src={require('../images/loader.gif')} />
: this.fetchResult()
}
</div>
);
}
尝试此代码
loadData() {
const {loading,posts}this.state
this.setState({!loading});
const path = `${url}/jira_jobs.php`;
axios.get(path)
.then(res => {
this.setState({
posts: res['data'],
!loading
});
})
.catch(err => {
console.error(err);
});
}
告诉我是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.