TypeError:无法读取未定义的属性“ textContent”

时间:2019-03-14 20:46:11

标签: javascript reactjs undefined

我收到此错误:

TypeError: Cannot read property 'textContent' of undefined

我知道responseDocument仍为undefined时会执行for循环。我该如何解决这个问题?

export default class App extends Component {

  constructor() {
    super();

    this.state = {
      newsFeed: {
        number: null,
        date: null,
        news: null,
      },
    };
  }

  fetchRssFeed() {

    const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
    const funkyGamesRssFeed = 'https://funkygames.de/rss.xml';
    const request = new Request(proxyUrl + funkyGamesRssFeed);

    return fetch(request).then((results) => {
      results
        .text()
        .then((str) => {
          let responseDocument = new DOMParser().parseFromString(str, 'application/xml');
          const newsItems = responseDocument.getElementsByTagName('item');

          let newsFeed = {
            number: newsItems.length,
            date: new Date(),
            news: [],
          };

          for (let i = 1; i < newsItems.length; i++) {

            let article = new Article();
            article.title = responseDocument.getElementsByTagName('title')[i].textContent;
            
            newsFeed.news.push(article);
          }

        }).catch((error) => console.log(error));
    });

  }

  componentDidMount() {
    this.fetchRssFeed().catch(e => console.log(e.message));
  }

1 个答案:

答案 0 :(得分:0)

当我这样做时,它对我有用:

for (let i = 1; i < newsItems.length; i++) {

        let article = new Article(
          responseDocument.getElementsByTagName('title')[i].textContent,
         );

        newsFeed.news.push(article);
      }