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

IT技术 javascript reactjs react-router
2021-05-18 12:27:34

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

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

这会将路径作为http://example.com/page.

但是由于我已经切换到使用 HashRouter,并且页面链接的生成方式类似于http://example.com/#/page,因此唯一回显的是“/”

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

2个回答

Route在 React-router v4 中,将三个 props 传递给它渲染的组件。其中之一是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,您将在页面上看到相同的路径。

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

React Router 提供了开箱即用的位置参数。

你可以像这样访问它 location.pathname

例如:如果组件是页面:

const {HashRouter, Route, Link} = ReactRouterDOM;
function Page({location}) {
  return <p>{location.pathname}</p>;
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <HashRouter>
        <div>
          <Route path="/page" component={Page} />
          <Link to='/page'>Link to Page</Link>
        </div>
      </HashRouter>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>

https://reacttraining.com/react-router/web/api/location