首页 > 解决方案 > 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();
        }

标签: javascriptreactjsstatesetstatejsonapi-resources

解决方案


您正在丢失此上下文,因此将其更改为箭头功能

  .then(() => {
                    this.setState({
                    sportsNewsFiltered: tempArr
                });
            });

推荐阅读