简体   繁体   English

使用 map 方法提取获取的数据

[英]Extract fetched data using map method

I am trying to fetching data from newsapi website.我正在尝试从 newsapi 网站获取数据。 It gives me data as array like object format.它给我数据作为数组,如 object 格式。

在此处输入图像描述

Now, my goal is to iterate this data and display my newsItem component.现在,我的目标是迭代此数据并显示我的 newsItem 组件。 Here is my code below.下面是我的代码。

export class News extends Component {
    constructor(){
        super()
        this.state = {
            articles: this.articles
        }
    }
    componentDidMount(){
        fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey=d21fe13361b94006b816f98a7c005003`)
        .then(res =>res.json())
        .then(data => this.setState({articles:data.articles}))
    }
  render() {
    return <div className='container my-3'>
        <h1 className='my-3'>NewsDonkey - Top Headlines</h1>
        <div className="row">
                {this.state.articles.map(element=> console.log(element))}
            <div className="col-md-4">
                <NewsItem/>
            </div>
        </div>
    </div>;
  }
}

export default News;

but, browser shows can't read properties of undefined.但是,浏览器显示无法读取未定义的属性。 Here is the error image.这是错误图像。 在此处输入图像描述

Now, you may say that data may be in object format that's why map method is not working.现在,您可能会说数据可能采用 object 格式,这就是 map 方法不起作用的原因。 I tried same coding in JS: articles.map(element=> console.log(element)) it extracted data perfectly.我在 JS 中尝试了相同的编码:articles.map(element=> console.log(element)) 它完美地提取了数据。 Please help me if you find any error in my coding.如果您在我的编码中发现任何错误,请帮助我。

The initial value of state.articles is this.articles which is undefined . this.articles state.articles它是undefined

At some point in the future, you'll assign a useful value to that property, but until then you can't treat it like the array it will be in the future but isn't yet.在将来的某个时候,您将为该属性分配一个有用的值,但在那之前您不能将其视为未来的数组,但现在还没有。

Test the value and do something different.测试值并做一些不同的事情。

eg例如

(!this.state.articles && <Loading />}
{this.state.articles && this.state.articles.map(element=> console.log(element))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM