【问题标题】:TypeError: Cannot read property 'length' of undefined in reactTypeError:无法读取反应中未定义的属性“长度”
【发布时间】:2019-12-28 01:36:36
【问题描述】:

我正在构建一个响应网站,该网站将从 newsapi 获取数据并显示在卡片上。在检查是否有一个长度之后,它将显示或显示替代响应,我收到此错误。 “TypeError:无法读取未定义的属性‘长度’”

这是我的编码:

import React, { Component } from 'react';


class Cards extends Component {
 constructor () {
   super();
   this.state = {
     post: [
 {
         author:"",
         discription:"",
         publishedAt:"",
         title:"",
         urlToImage:""
       }
]
   };
 }

componentDidMount() {
fetch('https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=GIVEN API KEY')
    .then(response => response.json())
    .then(response => this.setState({post :response}));
}
  render() {
    const { post } = this.state;
    const postlist = post.length ? (
      post.map(post => {
        return (
          <div>
            <div class="container card mb-3">
              <div class="row no-gutters">
                <div class="col-md-4">
                  <img src={post.urlToImage} class="card-img" alt="..."/>
                </div>
                <div class="col-md-8">
                <div class="card-body">
                  <h5 class="card-title">{post.title}</h5>
                  <p class="card-text">{post.description}</p>
                    <div class="row">
                      <p class="card-text col-6"><small class="text-muted">{post.author}</small></p>
                      <p class="card-text col-6"><small class="text-muted">{post.publishedAt}</small></p>
                    </div>
                </div>
                </div>
              </div>
            </div>
          </div>
        );
      })
    )
    : (
      <div class="center">No post yet!</div>
    );


    return (
      <div class="container">
        <h2>Latest News</h2>
        {postlist}
      </div>
    );
  }
}

export default Cards;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    解构this.state 时出错。 const { post } = this.state.post; 应该是 const { post } = this.state;

    编辑 从https://newsapi.org 看来,响应的结构将是{status: ..., totalArticles: ..., articles: [...]}。所以你的componentDidMount 应该是:

    componentDidMount() {
      fetch('https://newsapi.org/v2/top-headlines?' +
          'country=us&' +
          'apiKey=GIVEN API KEY')
        .then(response => response.json())
        .then(response => this.setState({post :response.articles}));
    }
    

    【讨论】:

    • 导致另一个错误“Unhandled Rejection (TypeError): this.setstate is not a function”
    • 正确的函数是this.setState,而不是this.setstate
    • 好的,现在地图出现错误。 “TypeError:post.map 不是函数”。
    • 您的 fetch 调用在完成时必须使用数组以外的其他内容填充 state.post
    • 已进行所有声明的更正,现在它正在工作,但显示的是“else”声明,而不是新闻帖子。当您检查浏览器反应开发者工具时,您可以看到正在加载数据。多次查看代码,但似乎找不到任何东西。
    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 2021-09-18
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多