简体   繁体   English

带有React Router v4的哈希路由器后退按钮

[英]Hash Router back button with React Router v4

I'm using HashRouter to setup my App like so: 我正在使用HashRouter设置我的应用程序,如下所示:

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. 效果很好,但是当我单击链接转到/ about并单击“后退”按钮时,没有任何反应。 How do I make it so my internet browser's back button will take me back to the previous page? 我该如何做才能使我的Internet浏览器的后退按钮将我带回到上一页? The app is built using create-react-app if that makes a difference. 如果有帮助,则使用create-react-app构建该应用程序。

Use Switch 使用开关

Switch is unique in that it renders a route exclusively. Switch的独特之处在于它专门呈现一条路由。 In contrast, every Route that matches the location renders inclusively. 相比之下,与位置匹配的每个Route都将进行包含性渲染。

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. 如果URL是/ about,则About,User和NoMatch将全部呈现,因为它们都与路径匹配。 This is by design, allowing us to compose Routes into our apps in many ways, like sidebars and breadcrumbs, bootstrap tabs, etc. 这是设计使然,使我们可以通过多种方式将Routes组合到我们的应用中,例如边栏和面包屑,引导程序标签等。

Now, if we're at /about, Switch will start looking for a matching Route. 现在,如果我们位于/ about,Switch将开始寻找匹配的Route。 Route path="/about" will match and Switch will stop looking for matches and render About 路线path =“ / about”将匹配,而Switch将停止寻找匹配并渲染“关于”

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>
)

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

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