reactjs - 尝试从 api 获取数据时出现未定义 - React

标签 reactjs

所以我尝试使用从 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

最佳答案

您的 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;

关于reactjs - 尝试从 api 获取数据时出现未定义 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53998407/

相关文章:

javascript - 在 Reactjs 中绑定(bind)后函数仍然未定义

css - React native, flex 和 width 父元素

javascript - 使变量在渲染函数中可用 | react js

reactjs - 使用 toHaveBeenCalledWith 检查 EventTarget

javascript - React Navigation 5,获取最接近的父导航器名称

javascript - 在 setState() 之后更新的状态不会作为 props 传递给组件

javascript - Reactjs this.state 给出 Uncaught TypeError : Cannot read property 'groupsData' of null

javascript - 当将状态作为 prop 传递给子组件时,React 如何维护状态封装?

javascript - 例如,如何将字符串形式的已解析 promise 对象映射到按钮上

javascript - 如何合并状态和 Prop ,然后将它们作为 Prop 传递?