You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件中react-router-dom v6.8.2的Link跳转后分类新闻不显示

问题解决:React新闻应用分类切换不生效

核心问题分析

  1. App.js组件缺失基础导入:类组件App未导入React.Component,导致组件无法正常初始化
  2. 翻页请求遗漏分类参数:News组件的翻页函数中,API请求URL未携带category参数,翻页时无法保持当前分类
  3. 未监听props变化触发数据更新:路由切换时News组件的category props发生变化,但类组件未通过生命周期函数触发重新请求,导致内容不更新

修复步骤及代码修改

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">&larr; 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 &rarr;</button>
        </div>

      </div>
    )
  }
}

修复说明

  • 封装fetchNews方法,确保所有API请求都携带category参数,避免分类丢失
  • 添加componentDidUpdate生命周期,监听category和country的props变化,自动触发对应分类的新闻请求
  • 优化翻页按钮禁用逻辑,防止请求不存在的页码
  • 动态修改页面标题,显示当前分类名称,提升用户体验

内容的提问来源于stack exchange,提问作者VijayA76R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:55:06