You need to enable JavaScript to run this app. React Router与Link组件点击后URL变化但页面不渲染问题排查
优惠活动
大模型
产品
解决方案
定价
更多

React Router与Link组件点击后URL变化但页面不渲染问题排查

Hey there, let's get to the bottom of this routing issue you're facing! I spot the exact problem in your code right away.

The Root Cause

The issue lies in how you're rendering your TopNav component. Right now, you're calling it as a regular JavaScript function with {TopNav()} instead of rendering it as a proper React component. When you do this, the <Link> elements inside TopNav don't get connected to the <BrowserRouter> context. That's why clicking the links updates the URL but doesn't trigger a re-render of the matching route—React Router can't detect the navigation event from those Links because they're outside the router's context scope.

The Simple Fix

Change {TopNav()} to <TopNav /> so React treats it as a component, which ensures all child elements (including the Links) inherit the BrowserRouter context. Here's your updated App.js code:

import {BrowserRouter, Switch, Route, Link} from 'react-router-dom';
import Home from './booking/Home';
import Login from './auth/Login';
import Register from './auth/Register';

const TopNav = () => (
  <div className="nav bg-light d-flex justify-content-between">
    <Link className="nav-link" to="/"> Home </Link>
    <Link className="nav-link" to="/login"> Login </Link>
    <Link className="nav-link" to="/register"> Register </Link>
  </div>
);

function App() {
  return (
    <BrowserRouter>
      <TopNav /> {/* This line is fixed */}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

Why This Works

When you render <TopNav />, React creates a component instance nested directly inside <BrowserRouter>. This gives all the <Link> elements inside TopNav access to the router's context, so when you click them, React Router can properly handle the navigation and instantly re-render the correct route component—no page refresh needed.

Give this a test, and your links should now update the page content right when you click them!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:32:33