我收到此错误:
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));
}
答案 0 :(得分:0)
当我这样做时,它对我有用:
for (let i = 1; i < newsItems.length; i++) {
let article = new Article(
responseDocument.getElementsByTagName('title')[i].textContent,
);
newsFeed.news.push(article);
}