1

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();
        }
4

2 回答 2

-1

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

  .then(() => {
                    this.setState({
                    sportsNewsFiltered: tempArr
                });
            });
于 2018-10-06T16:51:59.850 回答
-1

所以这在你的设置状态是指它在你想要的反应类中的函数,解决这个问题只需: () =>{...}

而不是:函数(){...}

于 2018-10-06T16:52:36.253 回答