【问题标题】:Implementing loader in React在 React 中实现加载器
【发布时间】:2020-08-23 12:44:25
【问题描述】:

我正在尝试实现一个加载器,如果组件尚未从 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)
    }
}

问题是这个等式总是给出错误,但是,console.log() 显示数组是空的,我错过了什么? 即使 newsList 各处的 .setstate 设置为 [],也会发生同样的事情。 我正在使用带有打字稿的 React。 提前致谢!

【问题讨论】:

  • 你的 API 是否给出了正确的响应?
  • 应该是if (newsList.length === 0) return &lt;Loader /&gt;
  • 是的,卡片被渲染了,问题只是这个方程,即使我将console.log()放在里面我也看不到它,因为它总是给出错误
  • @PrãtéékThápá,所以我将无法检查是否应该呈现一条消息:“您的查询没有消息”(这还没有实现,但它会)

标签: reactjs typescript react-state react-lifecycle


【解决方案1】:

您还可以创建一个特定的状态来处理这种情况。你要做的是:

  1. 添加另一个状态并将其设置为 true。

例子:

state = {
  newsList: [],
  currentCategory: '',
  loadingData: true
}
  1. 加载数据时将其设置为 false。

例子:

updateNews(){
    this.newsService.getByCategory(this.props.currentCategory).then((list: Article[]) => {
    console.log(list)
    this.setState({
      currentCategory: this.props.currentCategory,
      newsList: list,
      loadingData: false
    })
  })
};
  1. 在 if 语句中,确保加载为 false,然后再继续。

例子:

const { newsList } = this.state
  if (newsList.loadingData){
    return <Loader />
  }

【讨论】:

    【解决方案2】:

    javascript中的数组是对象,保存在堆上。当您使用“===”(严格相等运算符)时,您是在询问它们是否真的是相同的对象,但它们不是,因为它们将被保存到不同的内存地址。

    使用newsList.length === 0 代替检查数组是否为空

    通过一些技巧,您可以使用类型强制,但这不是最佳实践。 (松散相等运算符“==”确实类型强制)

    【讨论】:

      【解决方案3】:
      [] === []
      

      或

      <<everything>> === []
      

      返回错误

      除了

      const a = []
      a===a
      

      将返回 true

      阅读更多value versus reference

      【讨论】:

        猜你喜欢
        • 2023-01-03
        • 1970-01-01
        • 1970-01-01
        • 2020-01-22
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多