javascript - React setState reading as undefined after filtering through API response
问题描述
I'm trying to filter an api response in React to certain news items, but when I call the setState function my console is throwing the error that it cannot setState of property undefined. I'm new to React so excuse me if this is an obvious fix.
class LeagueTables extends Component {
constructor(props) {
super();
this.state = {
sportsNewsFiltered: []
};
this.mountNews = this.mountNews.bind(this);
}
mountNews() {
var tempArr = [];
var urlNews =
"https://newsapi.org/v2/top-headlines?sources=bbc-
sport&apiKey=" + SECRETS.API_KEY;
var reqNews = new Request(urlNews);
fetch(reqNews)
.then(response => response.json())
.then(function(json) {
for (var i = 0; i < json.articles.length; i++) {
if (json.articles[i].url.includes("football")) {
tempArr.push(json.articles[i]);
}
}
})
.then(function() {
this.setState({
sportsNewsFiltered: tempArr
});
});
}
componentDidMount() {
this.mountNews();
}
解决方案
您正在丢失此上下文,因此将其更改为箭头功能
.then(() => {
this.setState({
sportsNewsFiltered: tempArr
});
});
推荐阅读
- java - Java从带有GMT字符串的字符串中解析日期
- sql - 如何在 Oracle 中获取触发器的用户/创建日期
- react-native-android - 自动填充不适用于 android react native
- apache-spark - Spark:如何按键比较两个rdd
- apache-spark - Pyspark 数据框中的 Cache()
- html - 鼠标离开元素时弹出窗口消失
- css - 在本机反应中无法换行
- python - 如何在 scipy.optimize.minimize 上为 Powell 方法设置正确的方向向量?
- typescript - NextJS VSCode Typescript ==> 断点未绑定
- ios - 排错错误:UICollectionViewFlowLayout 的行为未定义,因为项目高度必须小于高度