>  Q&A  >  본문

React의 구성 요소는 상태 변경 후 변경되지 않습니다(comComponentDidMount 가져오기)

뉴스 앱을 만들기 위해 튜토리얼을 따르고 있습니다. newapi에서 데이터를 가져오고 있습니다. 제 코드는 튜토리얼과 동일하지만 상태(this.state.articles)를 업데이트한 후 구성 요소가 작동하지 않습니다. 변화. setState 함수를 사용했고, 콘솔에 상태를 기록해 보았습니다. 업데이트 후 상태는 괜찮아 보였고, 렌더링 메서드가 실행되었지만 아무것도 바뀌지 않았습니다. 뭔가 잘못되었을 수 있습니다

내 코드/구성요소

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粉384679266428일 전615

모든 응답(2)나는 대답할 것이다

  • P粉724737511

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

    안녕하세요 @Curious, 코드가 정확합니다

    만들때 주의하세요map

    고정(시뮬레이션) 목록인 this.articles을 사용하고 있습니다.

    이것이 didMount에서 변경한 상태이기 때문에 this.state.articles에서 this.state.articles中调用map를 호출해야 합니다

    회신하다
    0
  • P粉311464935

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

    this.articlesthis.state.articles 동일하지 않습니다.

    정적 속성이 있습니다 this.articles,你在渲染逻辑中使用了它 - this.articles.map(.... 가져오기 상태를 업데이트하는 중입니다(정상 작동).

    렌더링 로직을 업데이트하여 this.state.articles에서 데이터를 읽으면 작동합니다.

    회신하다
    0
  • 취소회신하다