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

ReactJS点击导航栏分类路由时News组件未重新加载更新问题

问题根本原因

  • 你修改的是App组件的实例属性this.category和this.uniqueKeyForRemountingNewsComponent,React类组件只有state或props发生变化时才会触发重新渲染,实例属性的修改React无法感知,所以传给News组件的category参数和key一直不会更新,News自然不会按照新分类重新加载。
  • 额外小错误:health分类的Route属性写错,exactpath应改为exact path。

推荐修复方案

直接用路由参数简化代码,无需写大量重复的Route规则,修改App.js代码如下:

import './App.css';
import React, { Component } from 'react'
import NavBar from './components/NavBar';
import News from './components/News';
import {
  BrowserRouter as Router,
  Switch,
  Route
} from "react-router-dom";

export default class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <NavBar/>
          <Switch>
            <Route exact path="/about">
              {/* 此处补充about页面的对应内容即可 */}
            </Route>
            {/* 匹配所有分类路由,提取路由参数作为分类值 */}
            <Route exact path="/:category">
              {(routeProps) => (
                <News
                  // 用分类名作为key,分类变化时自动重挂载News组件
                  key={routeProps.match.params.category}
                  pageSize={5}
                  country="in"
                  category={routeProps.match.params.category}
                />
              )}
            </Route>
            {/* 首页默认加载general分类新闻 */}
            <Route exact path="/">
              <News key="general" pageSize={5} country="in" category="general"/>
            </Route>
          </Switch>
        </div>
      </Router>
    )
  }
}

修复说明

路由切换时路由参数:category会发生变化,传给News组件的key会同步更新,React会直接卸载旧的News组件、挂载新的News实例,自动触发componentDidMount拉取对应分类的新闻数据,完全符合你的预期需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:36:02