简体   繁体   中英

Hash Router back button with React Router v4

I'm using HashRouter to setup my App like so:

import {HashRouter as Router, Route, Switch, Link} from 'react-router-dom';

const Routing = () => (
  <Router>
    <div>
    <Route exact path ="/" component = {App} />
    <Route path ="/about" component = {About} />
    </div>
  </Router>
)

It works great, but when I click a link to go to /about and then hit the back button nothing happens. How do I make it so my internet browser's back button will take me back to the previous page? The app is built using create-react-app if that makes a difference.

Use Switch

Switch is unique in that it renders a route exclusively. In contrast, every Route that matches the location renders inclusively.

This means that the way you are doing it all routes are being rendered because they match.

If the URL is /about, then About, User, and NoMatch will all render because they all match the path. This is by design, allowing us to compose Routes into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc.

Now, if we're at /about, Switch will start looking for a matching Route. Route path="/about" will match and Switch will stop looking for matches and render About

Your code should look like this

import {HashRouter as Router, Route, Switch, Link} from 'react-router-dom';

const Routing = () => (
  <Router>
    <Switch>
      <Route exact path ="/" component = {App} />
      <Route path ="/about" component = {About} />
    </Switch>
  </Router>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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