简体   繁体   English

React Router 和 Link 不渲染

[英]React Router and Link do not render

I'm working on a react app and I found my page does not render when the url changes.我正在开发一个反应应用程序,我发现当 url 更改时我的页面没有呈现。 See the code below, I have a navigagtion bar with three Link , when I click them, I can see that the url changes in the address bar, but the page is still staying the one from the old url.请看下面的代码,我有一个带有三个Link的导航栏,当我点击它们时,我可以看到地址栏中的 url 发生了变化,但页面仍然是旧 url 中的那个。 However if I refresh the page, then the corresponding page to the current url is rendered and presented.但是,如果我刷新页面,则会呈现并呈现与当前 url 对应的页面。

I saw a similar question but the method in it does not work for me, or maybe I use it in a wrong way?我看到了一个类似的问题,但其中的方法对我不起作用,或者我以错误的方式使用它? React Router or Link Not Rendered 反应路由器或链接未呈现

this is the code from my App.js :这是我的App.js中的代码:

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()}
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
      </Switch>
    </BrowserRouter>
  );
}

export default App;

What is your React Router version?你的反应路由器版本是什么? If it's React Router v6.如果是 React Router v6. You need to change it like this below:您需要像下面这样更改它:

<Route exact path="/" element={<Home />} />
<Route exact path="/login" element={<Login />} />
<Route exact path="/register" element={<Register />} />

Because using component is from React Router v5, the newest version using element因为 using component来自 React Router v5,所以使用element的最新版本

Hope it helps!希望能帮助到你!

Could you try to use JSX for your TopNav component?您可以尝试将 JSX 用于您的 TopNav 组件吗?

  return (
    <BrowserRouter>
      <TopNav/>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
      </Switch>
    </BrowserRouter>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM