ReactJs Router更改url而不更改页面

时间:2020-09-27 19:44:20

标签: javascript reactjs routes react-router react-router-dom

我正在构建一个投资组合网站,并使用react BrowserRouter,Link和Switch来管理我的网站路由。我的问题是,当我单击“项目”链接时,它在url上改变了,但是在视图中却没有改变,但是当我刷新页面有效。

这是我App.js中当前的路由情况。

import React, { Component } from 'react';

import NavBar from './Components/NavBar/NavBar'
import Home from './Components/Home/Home';
import Projects from './Components/Projects/Projects';

import { BrowserRouter ,Switch, Route, } from 'react-router-dom';

class App extends Component {
  
  render() {
    return (
      <div className="App">
        <NavBar />
        <BrowserRouter>
          <Switch>
            <Route path="/" component={Home} exact={true} />
            <Route path="/projects" component={Projects} /> 
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;


这就是我的Navbar.js的样子。

import React, {useState} from 'react';
import { NavLink, BrowserRouter } from 'react-router-dom'
import { Link } from 'react-scroll';

function NavBar() {
  const [navbar,setNavbar] = useState(false)

  const changeBackground = () => {
    if(window.scrollY >= 100) {
      setNavbar(true)
    } else {
      setNavbar(false)
    }
  }

  window.addEventListener('scroll', changeBackground)

  return(
    <BrowserRouter>
      <ul className="nav bg-white sticky-top nav-tabs nav-justified">
        <li className="nav-item">
          <Link 
            className={navbar ? "nav-link text-dark home" : "nav-link text-secondary home"}
            to="home"
            href="/"
            smooth={true}
            offset={50}
            duration={500}>
            Home
          </Link>
        </li>

        <li className="nav-item">
        <Link 
            className={navbar ? "nav-link text-dark home" : "nav-link text-secondary about"}
            to="about"
            smooth={true}
            offset={50}
            duration={500}>
            About
          </Link>
        </li>

        <li className="nav-item">
          <NavLink to="/projects">Projects</NavLink> //This is the link that won't work. 
        </li>

        <li className="nav-item">
         <Link 
            className={navbar ? "nav-link text-dark home" : "nav-link text-secondary contact"}
            to="contact"
            smooth={true}
            offset={50}
            duration={500}>
            Contact
          </Link>
        </li>
      </ul>
    </BrowserRouter>
      
  
  )
}

export default NavBar

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

问题是您要定义两个不同的BrowserRouter。您所有的路由逻辑都应在一个BrowserRouter下:

应用程序应如下所示:

class App extends Component {
  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <NavBar />
          <Switch>
            <Route path="/" component={Home} exact={true} />
            <Route path="/projects" component={Projects} /> 
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

和NavBar不应包含包装的BrowserRouter