简体   繁体   English

在ReactJS应用中“ TypeError:无法读取未定义的属性'map'”

[英]“TypeError: Cannot read property 'map' of undefined” In reactjs app

I keep getting this error. 我不断收到此错误。 It worked previously, but over time it started giving me the error. 以前它可以工作,但是随着时间的流逝,它开始给我错误。

I tried changing the arrow function into a standard function. 我尝试将箭头功能更改为标准功能。 I also tried using the same code in a different app, and that worked. 我也尝试在不同的应用程序中使用相同的代码,并且行得通。 But for some reason I only get the error in this app. 但是由于某种原因,我只会在此应用中收到错误消息。

import React, { Component } from 'react';
import NewSingle from './NewSingle';
import Error from './Error';

class News extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: [],
      error: false,
    };
  }

  componentDidMount() {
    const url = `https://newsapi.org/v2/${this.props.news.type}?${this.props.news.query}&apiKey=ae3aff618e7d4b71b666bd9d0b10f053`;

    fetch(url)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.setState({
          news: data.articles
        })
      })
      .catch((error) => {
        this.setState({
          error: true
        })
      });
  }

  renderItems() {
    if (!this.state.error) {
      return this.state.news.map((item) => (
        <NewSingle key={item.url} item={item} />
      ));
    } else {
      return <Error />
    }
  }

  render() {
    return (
      <div className="row">
        {this.renderItems()}
      </div>
    );
  }
}

export default News;
import React from 'react';

const NewSingle = ({item}) => (
    <div className='col s4'>
        <div className='card'>
            <div className='card-image'>
                <img src={item.urlToImage} alt={item.title} />
                <span className='card-title'>{item.source.name}</span>
            </div>
            <div className='card-content'>
            <p>{item.title}</p>
            </div>
            <div className='card-action'>
                <a href={item.url} target='_blank' rel="noopener noreferrer">Full article</a>
            </div>
        </div>
    </div>
);

export default NewSingle;

The api is supposed to render news data from the api. 该API应该呈现来自该API的新闻数据。

Try protecting the code by 尝试通过以下方式保护代码

if (!this.state.error) {
      return this.state.news.length> 0 && this.state.news.map((item) => (
        <NewSingle key={item.url} item={item} />
      ));

由于error仅在获取后设置,并且您不检查news是否真正包含数据,因此您应该在return渲染之前添加条件,或将renderItems中的条件更改为if (!this.state.error && (this.state.news && this.state.news.length))

I don't think fetch works the way you are expecting. 我认为fetch并不像您期望的那样工作。 Even on a bad request it will not throw an error, meaning data.articles will sometimes be undefined. 即使是错误的请求,它也不会引发错误,这意味着data.articles有时是不确定的。 fetch sets response.ok depending on if it was successful, so you can use that to check before proceeding. fetch根据response.ok是否成功来设置response.ok ,因此您可以在继续操作之前使用它进行检查。

Try changing your fetch to something like this: 尝试将您的抓取更改为以下内容:

fetch(url)
  .then((response) => {
    // Add this check and throw an error if it fails
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response.json();
  })
  .then((data) => {
    this.setState({
      news: data.articles
    })
  })
  .catch((error) => {
    this.setState({
      error: true
    })
  });

Another thing to point out, newsapi.org requires q=query so make sure this.props.news.query includes q=... , or add it before like: https://newsapi.org/v2/${this.props.news.type}?q=${this.props.news.query} 需要指出的另一件事是,newsapi.org需要q=query因此请确保this.props.news.query包含q=... ,或在之前添加它,例如: https://newsapi.org/v2/${this.props.news.type}?q=${this.props.news.query} : this.props.news.query https://newsapi.org/v2/${this.props.news.type}?q=${this.props.news.query}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM