使用 React Router 4 和哈希路由获取页面位置 [英] Get page location with React Router 4 and Hash routing

查看:74
本文介绍了使用 React Router 4 和哈希路由获取页面位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

解决方案

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

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

像这样:

从'react'导入React;从'react-dom'导入{渲染};import { Route, HashRouter as Router, Switch } from 'react-router-dom';const Child = ({ match }) =>{返回<p>{match.url}</p>;};const App = () =>(<路由器><开关><路由精确路径='/' component={Child}/><路由精确路径='/test1' component={Child}/><路由精确路径='/test2' component={Child}/></开关></路由器>);render(, document.getElementById('root'));

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

将右侧预览部分的路由改为/ or /test1 or /test2,你会看到同样的页面上显示的路径.

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

I want to get the location of the page I'm on in order to set up conditional rendering. Originally, I had something set up like this

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

And that would echo out the path as http://example.com/page.

But since I've switched to using HashRouter, and page links are generated like http://example.com/#/page, the only thing that echoes out is "/"

How do I get the location of the page after the hash?

解决方案

Route in React-router v4 passes three props to the component it renders. One of these is the match object. It contains information about how the current path was matched.

In your case, you can use match.path or match.url to get the location of the page.

Something like this:

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

Working code is available here: https://codesandbox.io/s/3xj75z41z1

Change the route in the preview section on the right to / or /test1 or /test2, and you'll see the same path displayed on the page.

Hope this helps. Cheers! :)

这篇关于使用 React Router 4 和哈希路由获取页面位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆