React Router:渲染没有页面刷新的新视图

时间:2017-07-25 14:19:38

标签: reactjs react-router

React Route Load Test

您好!我尝试做的是重写我的react-router,以便NavLink在点击时呈现一个全新的页面,而不是在div的底部呈现,如上面的gif所示。

这是我的主要App.js组件的内容:

import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Home from './Home.js';
import About from './About.js';
import September from './September.js';
import Trilogy from './Trilogy.js';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Switch>
            <Route exact path='/' component={Home} />
            <Route path='/about/' component={About} />
            <Route path='/september/' component={September} />
            <Route exact path='/september/trilogy/' component={Trilogy} />
          </Switch>
        </div>
      </Router>
    );
  }
}
export default App;

Home组件的代码,其中包含主页中使用的NavBar。

import React, { Component } from 'react';
import { BrowserRouter as Router, NavLink, Switch, Route } from 'react-router-dom';
import logo from './logo.png';
import About from './About.js';
import September from './September.js';
import Trilogy from './Trilogy.js';

let NavBar = () => {
  return (
    <div>
      <h2 className="container2"><NavLink to='/about/'>About</NavLink> </h2>
      <img src={logo} className="somersetLogo" alt="somersetLogo" />
      <h2 className="container" ><a href="mailto:contact@somersetproductions.co" className="mailto">Contact</a></h2>
    </div>
  )
}

class Home extends Component {
  render() {
    return (
      <Router>
        <div>
          <NavBar />
          <Switch>
            <Route exact path='/about/' component={About} />
          </Switch>
        </div>
      </Router>
    )
  }
}

export default Home;

知道出了什么问题吗?任何帮助,将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

如果您使用的是反应路由器v4或更高版本,它应该是这样的。

import { Link } from 'react-router-dom';

<Link to='/about'>
    About
</Link>

为什么要在Home组件中再次定义路由器,这是不需要的。在App组件中保留路由配置就足够了。希望这可以帮助。快乐的编码!