首页 > 解决方案 > TypeError: Cannot read properties of undefined (reading 'map') 。几个小时前我回来时它运行得很好它抛出了这个错误

问题描述

import React, { Component } from "react";
import Nitems from "./Nitems";
import Loading from "./Loading";
import './Font.css'
import PropTypes from 'prop-types'


export class News extends Component {
  static defaultProps={
    country: "in",
    category: "general"
  }
  static propTypes={
    country: PropTypes.string,
    category: PropTypes.string
  }
  constructor() {
    super();
    console.log("Hii this is a constructor");
    this.state = {
      articles: [],
      loading: false,
      page: 1,
    };
  }
  async componentDidMount() {
    this.props.setProgress(10)
    let url =
    `https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=${this.props.apikey}&pagesize=12`;
    this.setState({loading: true})
    let data = await fetch(url);
    this.props.setProgress(30)
    let parsedata = await data.json();
    this.props.setProgress(70)
    this.setState({
      articles: parsedata.articles,
      totalarticles: parsedata.totalResults,
      loading: false
    });
    this.props.setProgress(100)
  }
  previouspage = async () => {
    this.props.setProgress(10)
    let url = `https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}$apiKey=${this.props.apikey}&page=${
      this.state.page - 1
    }&pagesize=12`;
    this.setState({loading: true})
    let data = await fetch(url);
    let parsedata = await data.json();
    console.log(parsedata);
    this.setState({
      page: this.state.page - 1,
      articles: parsedata.articles,
      loading: false
    });
    this.props.setProgress(100)
  };
  
  nextpage = async () => {
    this.props.setProgress(10)
    if (this.state.page + 1 > Math.ceil(this.state.totalarticles / 12)) {
      
    } 
    else {
      let url = `https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=${this.props.apikey}&page=${
        this.state.page + 1
      }&pagesize=12`;
      
      this.setState({loading: true})
      let data = await fetch(url);
      let parsedata = await data.json();
      console.log(parsedata);
      this.setState({
        page: this.state.page + 1,
        articles: parsedata.articles,
        loading: false
      });
      this.props.setProgress(100)
    }
  };
  render() {
    return (
      <div className="container ">
        <h3 className="my-3" className="text-center" style={{margin: "18px 0px", fontFamily:" Permanent Marker", fontSize: "45px"}}>Top Headlines </h3>
        {this.state.loading && <Loading/>}
        <div className="row">
          {!this.state.loading && this.state.articles.map((element) => {
            return (
              <div className="col-md-4" key={element.url}>
                <Nitems
                  title={element.title.slice(0, 50)}
                  description={
                    element.description
                      ? element.description.slice(0, 45)
                      : "Description is not available. The ADP"
                  }
                  img={element.urlToImage}
                  nurl={element.url}
                  date={element.publishedAt}
                  author={element.source.name}
                ></Nitems>
              </div>
            );
          })}
        </div>
        <div class="d-flex justify-content-between">
          <button
            disabled={this.state.page <= 1}
            type="button"
            class="btn btn-danger"
            onClick={this.previouspage}
          >
             Previous
          </button>
          <button disabled={(this.state.page + 1 > Math.ceil(this.state.totalarticles / 12))} type="button" class="btn btn-danger" onClick={this.nextpage}>
            Next 
          </button>
        </div>
      </div>
    );
  }
}

export default News;

几个小时前当我回来时它运行得很好它抛出了这个错误。渲染部分保持不变。你能检查一下这段代码有什么问题吗?我认为这是一个关于错误的 API。因为当我试图通过道具传递我的 api 密钥时,就会出现这个错误。我将 api 密钥保存到 .env.loacl 文件中。你能检查一下这段代码有什么问题吗?

标签: reactjs

解决方案


发生这种情况是因为以下 >articles: [],loading: false,

请注意,您唯一的验证是 if !this.state.loadingthen 尝试映射 over articles,但由于 urloading以 false 开始,它将通过 ur 条件g,然后 urarticles尚未安装,因为它开始为空 [],因此它尝试映射到空数组和react 会抛出这个错误。

解决此问题的一种方法是>>!this.state.loading && this.state.articles.length > 0 && ...proceed to map

有了这个,您将加倍检查文章是否已被填充,并且当其中包含值时,他将自动开始重新渲染。


推荐阅读