使用React Router 4和哈希路由获取页面位置

Bluebrooklynbrim

我想获取我所在页面的位置,以便设置条件渲染。本来我有这样的设置

const currentPath = window.location.pathname;
...
<h1>{currentPath}</h1>

那样会回荡路径http://example.com/page

但是,由于我已切换为使用HashRouter,并且生成了页面链接,如http://example.com/#/page,所以唯一回显的是“ /”

哈希后如何获取页面的位置?

希希尔

Route在React-router v4中,将三个道具传递到它渲染的组件。其中之一是match对象。它包含有关如何匹配当前路径的信息。

在您的情况下,您可以使用match.pathmatch.url获取页面的位置。

像这样:

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

const Child = ({ match }) => {
  return <p>{match.url}</p>;
};

const App = () => (
  <Router>
    <Switch>
      <Route exact path='/' component={Child} />
      <Route exact path='/test1' component={Child} />
      <Route exact path='/test2' component={Child} />
    </Switch>
  </Router>
);

render(<App />, document.getElementById('root'));

可在此处找到工作代码:https : //codesandbox.io/s/3xj75z41z1

右侧预览部分路线更改为//test1或者/test2,你会看到相同的路径显示在页面上。

希望这可以帮助。干杯! :)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章