簡體   English   中英

使用 map 方法提取獲取的數據

[英]Extract fetched data using map method

我正在嘗試從 newsapi 網站獲取數據。 它給我數據作為數組,如 object 格式。

在此處輸入圖像描述

現在,我的目標是迭代此數據並顯示我的 newsItem 組件。 下面是我的代碼。

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;

但是,瀏覽器顯示無法讀取未定義的屬性。 這是錯誤圖像。 在此處輸入圖像描述

現在,您可能會說數據可能采用 object 格式,這就是 map 方法不起作用的原因。 我在 JS 中嘗試了相同的編碼:articles.map(element=> console.log(element)) 它完美地提取了數據。 如果您在我的編碼中發現任何錯誤,請幫助我。

this.articles state.articles它是undefined

在將來的某個時候,您將為該屬性分配一個有用的值,但在那之前您不能將其視為未來的數組,但現在還沒有。

測試值並做一些不同的事情。

例如

(!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