如何解决在React中实现loader
我正在尝试实现一个加载器,如果该组件尚未从API接收数据,则会显示该加载器。这是我的代码:
import React,{Component} from 'react'
import './news-cards-pool.css'
import NewsService from '../../services/news-service'
import NewsCard from '../news-card'
import Loader from '../loader'
interface NewsCardsPoolProps {
currentCategory: string
}
interface NewsCardsPoolStates {
newsList: Article[],currentCategory: string,}
interface Article {
title: string,description: string,url: string,image: string
}
export default class NewsCardsPool extends Component<NewsCardsPoolProps,NewsCardsPoolStates> {
newsService = new NewsService()
state = {
newsList: [],currentCategory: ''
}
componentDidUpdate(prevProps: Readonly<NewsCardsPoolProps>) {
if(prevProps.currentCategory !== this.props.currentCategory) {
this.updateNews()
}
}
componentDidMount() {
this.updateNews()
}
updateNews(){
this.newsService.getByCategory(this.props.currentCategory).then((list: Article[]) => {
console.log(list)
this.setState({
currentCategory: this.props.currentCategory,newsList: list
})
})
}
renderItems(newsList: Article[]){
const itemsList = newsList.map((article: Article) => {
return(
<div className="col-sm-12 col-md-6 col-lg-3 card-container">
<div className="card">
<img src={article.image} alt="icon" />
<div className="info">
<h5><a href={article.url}>{article.title}</a></h5>
<p>{article.description}</p>
</div>
</div>
</div>
)
})
return itemsList
}
render() {
const { newsList } = this.state
if (newsList === []){
return <Loader />
}
return this.renderItems(newsList)
}
}
问题在于此等式始终给出false,但是console.log()显示数组为空,我缺少什么? 即使将各处的newsList的.setstate设置为[],也会发生相同的情况。 我正在使用带有脚本的React。 预先感谢!
解决方法
您还可以创建一个特定的状态来处理这种情况。您要做的是:
- 添加其他状态并将其设置为true。
示例:
state = {
newsList: [],currentCategory: '',loadingData: true
}
- 在加载数据时将其设置为false。
示例:
updateNews(){
this.newsService.getByCategory(this.props.currentCategory).then((list: Article[]) => {
console.log(list)
this.setState({
currentCategory: this.props.currentCategory,newsList: list,loadingData: false
})
})
};
- 在if语句中,请确保加载为假,然后再继续。
示例:
const { newsList } = this.state
if (newsList.loadingData){
return <Loader />
}
,
javascript中的数组是对象,保存在堆中。当您使用“ ===“(严格相等运算符)时,您会问它们是否确实是相同的对象,而不是,因为它们将保存到不同的内存地址中。
使用newsList.length === 0
来检查数组是否为空
通过一些技巧,您可以使用类型强制,但这不是最佳实践。 (宽松的等号运算符“ ==”确实会强制输入)
,[] === []
或
<<everything>> === []
返回假
除
const a = []
a===[]
将返回true
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。