首页 > 解决方案 > 尝试从 api 获取数据时未定义 - React

问题描述

所以我试图用从 API 获得的数据设置一个变量。

当我通过控制台将其登录到我的浏览器时,一切正常,但是当我尝试在 React 上设置我的变量时,该变量最终无法识别。有人能告诉我我在这里想念什么吗?

这是我的代码:

import React from 'react'

let news
function getNews () {
  fetch(
    'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
  )
    .then(res => res.json())
    .then(data => {
      news = data
      return news
    })
}

getNews()
class NewsApi extends React.Component {
  render () {
    return <div />
  }
}

export default NewsApi

标签: reactjs

解决方案


您的 getNews 函数是异步的。您应该使用状态来保存数据。因此,一旦获取数据,您就可以使用组件中的数据。

import React from 'react';

class NewsApi extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            news: []
        };
        this.getNews = this.getNews.bind(this);
    }

    componentDidMount() {
        this.getNews()
    }

    getNews() {
        fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
            .then(res => res.json())
            .then((data) => {
                this.setState({news:data.articles});
            });
    }

    render() {
        console.log(this.state.news)
        return (
            <div></div>
        );
    }
}

export default NewsApi;

推荐阅读