【问题标题】:Get page location with React Router 4 and Hash routing使用 React Router 4 和哈希路由获取页面位置
【发布时间】:2018-03-12 09:10:35
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    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,您将在页面上看到相同的路径。

    希望这会有所帮助。干杯! :)

    【讨论】:

    • 谢谢!有没有办法在类组件中使用match.url
    • 不客气! :) match 只是 Route 组件传递的一个道具。在类组件中,您可以通过this.props.match.url
    【解决方案2】:

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

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

    例如:如果组件是Page:

    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

    【讨论】:

    • 虽然这是有道理的,但我不断收到 Unexpected use of 'location' 错误,除非我使用 window.location,否则它只会消失,它再次只为所有哈希路由返回“/”。另外,我如何将位置作为参数传递给反应组件类?
    • 如果组件在路由中,它已经是一个prop。您收到 Unexpected use of location 是因为您没有使用道具,而是尝试访问全局对象。
    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2015-03-30
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多