首页  >  问答  >  正文

React中的组件在状态改变后未发生变化(componentDidMount fetch)

我正在按照教程制作一个新闻应用程序,我正在从newapi获取数据,我的代码与教程中的代码相同,但是在我更新状态(this.state.articles)后,我的组件没有改变。我使用了setState函数,我尝试在控制台记录状态,状态在更新后看起来很好,render方法运行了,但是没有改变任何内容,可能出了什么问题

我的代码/组件

import React, { Component } from 'react'
import NewsItem from './NewsItem'

export default class News extends Component {
    articles = [
        {
            "source": {
                "id": "espn-cric-info",
                "name": "ESPN Cric Info"
            },
            "author": null,
            "title": "PCB hands Umar Akmal three-year ban from all cricket | ESPNcricinfo.com",
            "description": "Penalty after the batsman pleaded guilty to not reporting corrupt approaches | ESPNcricinfo.com",
            "url": "http://www.espncricinfo.com/story/_/id/29103103/pcb-hands-umar-akmal-three-year-ban-all-cricket",
            "urlToImage": "https://a4.espncdn.com/combiner/i?img=%2Fi%2Fcricket%2Fcricinfo%2F1099495_800x450.jpg",
            "publishedAt": "2020-04-27T11:41:47Z",
            "content": "Umar Akmal's troubled cricket career has hit its biggest roadblock yet, with the PCB handing him a ban from all representative cricket for three years after he pleaded guilty of failing to report det… [+1506 chars]"
        },
        {
            "source": {
                "id": "espn-cric-info",
                "name": "ESPN Cric Info"
            },
            "author": null,
            "title": "What we learned from watching the 1992 World Cup final in full again | ESPNcricinfo.com",
            "description": "Wides, lbw calls, swing - plenty of things were different in white-ball cricket back then | ESPNcricinfo.com",
            "url": "http://www.espncricinfo.com/story/_/id/28970907/learned-watching-1992-world-cup-final-full-again",
            "urlToImage": "https://a4.espncdn.com/combiner/i?img=%2Fi%2Fcricket%2Fcricinfo%2F1219926_1296x729.jpg",
            "publishedAt": "2020-03-30T15:26:05Z",
            "content": "Last week, we at ESPNcricinfo did something we have been thinking of doing for eight years now: pretend-live ball-by-ball commentary for a classic cricket match. We knew the result, yes, but we tried… [+6823 chars]"
        }
    ]

    constructor() {
        super();
        this.state = {
            articles: this.articles,
            loading: false
        }
    }

    async componentDidMount() {
        const URL = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey="
        let data = await fetch(URL);
        let parsedData = await data.json()
        this.setState({
            articles: parsedData.articles
        })
        console.log(this.state.articles)
    }
    render() {
        console.log("render")
        return (
            <div>
                <div className="container">
                    <h2 className='my-4 mx-4'> NewsMonkey - Top Headlines </h2>
                    <div className="row">
                        {this.articles.map((elem) => {
                            return <div className="col-md-4" key={elem.url}>
                                <NewsItem title={elem.title?elem.title.slice(42):""} desc={elem.description?elem.description.slice(0, 88): ""} url={elem.url} imgURL={elem.urlToImage} />
                            </div>
                        })}
                    </div>
                </div>
            </div>
        )
    }
}

P粉384679266P粉384679266425 天前611

全部回复(2)我来回复

  • P粉724737511

    P粉7247375112023-09-12 17:52:54

    嗨 @Curious,你的代码是正确的

    只需要在制作map时注意一下

    你正在使用this.articles,这是一个固定(模拟)列表

    你需要在this.state.articles中调用map,因为这是你在didMount中更改的状态

    回复
    0
  • P粉311464935

    P粉3114649352023-09-12 16:04:16

    this.articlesthis.state.articles 不是相同的。

    你有一个静态属性 this.articles,你在渲染逻辑中使用了它 - this.articles.map(...。你的 fetch 正在更新状态(正常操作)。

    更新你的渲染逻辑,从 this.state.articles 读取数据,然后它应该可以工作。

    回复
    0
  • 取消回复