React类组件中react-router-dom v6.8.2的Link跳转后分类新闻不显示
问题解决:React新闻应用分类切换不生效
核心问题分析
- App.js组件缺失基础导入:类组件
App未导入React.Component,导致组件无法正常初始化 - 翻页请求遗漏分类参数:
News组件的翻页函数中,API请求URL未携带category参数,翻页时无法保持当前分类 - 未监听props变化触发数据更新:路由切换时
News组件的categoryprops发生变化,但类组件未通过生命周期函数触发重新请求,导致内容不更新
修复步骤及代码修改
1. 修复App.js的导入问题
在App.js顶部补充React核心导入:
import React, { Component } from "react"; // 新增该行 import NavBar from "./components/NavBar"; import News from "./components/News"; import { Route, Routes } from "react-router-dom"; export default class App extends Component { // 原有代码保持不变 }
2. 重构News组件,统一请求逻辑并监听props变化
修改News.js,封装统一请求方法并添加props变化监听:
import React, { Component } from 'react' import NewsItem from './NewsItem' import Spinner from './Spinner'; import PropTypes from 'prop-types' export default class News extends Component { static defaultProps = { country:'in', pageSize:8, category:'general' } static propTypes = { country: PropTypes.string, pageSize:PropTypes.number, category:PropTypes.string, } constructor() { super(); this.state = { articles: [], loading: false, page: 1, totalResults: 0 } } // 封装统一的新闻请求方法 fetchNews = async (page) => { this.setState({ loading: true }); const url = `https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=**writeyourapikey**&page=${page}&pageSize=${this.props.pageSize}`; const data = await fetch(url); const parseData = await data.json(); this.setState({ articles: parseData.articles, totalResults: parseData.totalResults, loading: false, page: page }); } componentDidMount() { this.fetchNews(1); } // 监听props变化,分类/国家变更时重新请求第一页数据 componentDidUpdate(prevProps) { if (prevProps.category !== this.props.category || prevProps.country !== this.props.country) { this.fetchNews(1); } } handleNextClick = async () => { if (this.state.page < Math.ceil(this.state.totalResults / this.props.pageSize)) { this.fetchNews(this.state.page + 1); } } handlePreClick = async () => { if (this.state.page > 1) { this.fetchNews(this.state.page - 1); } } render() { const categoryTitle = this.props.category.charAt(0).toUpperCase() + this.props.category.slice(1); return ( <div className='container my-3'> <h2 className="text-center">HeadlineHunter - Top {categoryTitle} News</h2> {this.state.loading && <Spinner/>} <div className="row"> {!this.state.loading && this.state.articles.map((element) => ( <div className="col-md-4" key={element.url}> <NewsItem title={element.title || ""} description={element.description || element.title} imgUrl={element.urlToImage} newsUrl={element.url} /> </div> ))} </div> <div className="container d-flex justify-content-between "> <button disabled={this.state.page <= 1} className="btn btn-dark" onClick={this.handlePreClick} type="button">← Previous</button> <button disabled={this.state.page >= Math.ceil(this.state.totalResults / this.props.pageSize)} className="btn btn-dark" onClick={this.handleNextClick} type="button">Next →</button> </div> </div> ) } }
修复说明
- 封装
fetchNews方法,确保所有API请求都携带category参数,避免分类丢失 - 添加
componentDidUpdate生命周期,监听category和country的props变化,自动触发对应分类的新闻请求 - 优化翻页按钮禁用逻辑,防止请求不存在的页码
- 动态修改页面标题,显示当前分类名称,提升用户体验
内容的提问来源于stack exchange,提问作者VijayA76R
相关产品推荐
相关产品推荐

