我想获取我所在页面的位置,以便设置条件渲染。最初,我有这样的设置
const currentPath = window.location.pathname;
...
<h1>{currentPath}</h1>
这会将路径回显为 http://example.com/page
。
但是由于我已经改用 HashRouter,并且页面链接是像 http://example.com/#/page
那样生成的,所以唯一回显的是“/”
如何获取哈希后页面的位置?
最佳答案
React-router v4 中的
Route
将三个 props 传递给它渲染的组件。其中之一是 match
对象。它包含有关当前路径如何匹配的信息。
就您而言,您可以使用 match.path
或 match.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
,你会看到相同的结果页面上显示的路径。
希望这有帮助。干杯! :)
关于javascript - 使用 React Router 4 和哈希路由获取页面位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231521/