反应路由器V5更新URL但不刷新页面

时间:2020-08-19 09:36:58

标签: javascript reactjs react-router

反应路由器不会更新视图,而是会更改网址。

Navbar.js:

import React from "react";
import logo from "../Assets/imgs/Logo/WHITELOGOkatman 1.png";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
class Navbar extends React.Component {
  render() {
    return (
      <div className="header">
        <img className="logo" src={logo} alt="logo" />
        <Router>
          <nav>
            <ul className="nav_links">
              <Link to="/">
                <li>Home</li>
              </Link>
              <Link to="/process">
                <li>Process</li>
              </Link>
              <Link to="/career">
                <li>Career</li>
              </Link>
              <Link to="/about">
                <li>About</li>
              </Link>
            </ul>
          </nav>
        </Router>
      </div>
    );
  }
}
export default Navbar;

这是我的App.js

import React from "react";
import "./App.css";
import "./Components/Styles/style.css";
import "bootstrap/dist/css/bootstrap.css";
import Navbar from "./Components/Navbar";
import About from "./Components/About";
import Home from "./Components/Home";
import Career from "./Components/Career";
import Footer from "./Components/Footer";
import notFoundPage from "./Components/404";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
function App() {
  return (
    <div className="App">
      <Navbar />
      <Router>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/career" component={Career} />
          <Route path="/notfound" component={notFoundPage} />
        </Switch>
      </Router>
      <Footer />
    </div>
  );
}

export default App;

我尝试过的事情:

  1. 我尝试使用withRouter将我渲染的所有组件导出到Router中。页面仍然没有重新加载。
  2. 我曾尝试将路由器组件设为顶级组件,但这没用。
  3. 我曾尝试将li项作为链接,但这并没有达到我的期望。
  4. 我尝试了一些解决方法,例如在链接标签的顶部添加一个开关,然后从路由器标签中移除该开关,但仍然无济于事。
  5. 我还尝试过切换路线的顺序,以使路线尽头成为家。还是一无所有。

1 个答案:

答案 0 :(得分:0)

请尝试以下两种操作:

  • 首先确保您的路线顺序如下:
<Switch>
  <Route path="/about" component={About} />
  <Route path="/career" component={Career} />
  <Route path="/notfound" component={notFoundPage} />
  <Route exact path="/" component={Home} />
</Switch>
  • <Router>移到<Nav>内,然后用<App><Router>内的所有东西包起来...如下:
function App() {
  return (
    <Router>
      <div className="App">
        <Navbar />
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
            <Route path="/career" component={Career} />
            <Route path="/notfound" component={notFoundPage} />
          </Switch>
        <Footer />
      </div>
    </Router>
  );
}

我认为值得注意的是,根据我的经验,我逐渐意识到<Router>只会生一个孩子。因此在您的情况下,您两次使用<Router>


我可能还想通过将<Router>放在index.js文件中来进一步简化它:

ReactDOM.render(
   <Router>
      <App />
   </Router>,
   containerElement
);