React组件state更新后未渲染问题(componentDidMount数据获取场景)
问题:React组件更新state后界面无变化,控制台显示state已更新且render执行
问题原因
你在componentDidMount中成功通过setState更新了this.state.articles,但渲染界面时遍历的是类的实例属性this.articles(初始硬编码的测试数据),而非状态中的this.state.articles。这就导致即使状态更新,界面依然展示旧的硬编码内容。
另外补充一个细节:setState是异步操作,你在setState后直接console.log(this.state.articles)打印的是更新前的旧值,若要确认更新后的状态,应该使用setState的回调函数。
修正方案
- 在
render方法中,将遍历的数据源从this.articles改为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 }, () => { // 在setState的回调中打印更新后的state 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"> {/* 这里改为遍历state中的articles */} {this.state.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> ) } }
内容的提问来源于stack exchange,提问作者Curious
相关产品推荐
相关产品推荐

