React Router v4 - 如何获取当前路由? [英] React Router v4 - How to get current route?
本文介绍了React Router v4 - 如何获取当前路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 <AppBar/>
中显示一个 title
,它以某种方式从当前路由传入.
I'd like to display a title
in <AppBar />
that is somehow passed in from the current route.
在 React Router v4 中,<AppBar/>
如何将当前路由传递给它的 title
属性?
In React Router v4, how would <AppBar />
be able to get the current route passed into it's title
prop?
<Router basename='/app'>
<main>
<Menu active={menu} close={this.closeMenu} />
<Overlay active={menu} onClick={this.closeMenu} />
<AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
<Route path='/customers' component={Customers} />
</main>
</Router>
有没有办法从 <Route/>
上的自定义 prop
传递自定义标题?
Is there a way to pass a custom title from a custom prop
on <Route />
?
推荐答案
在 react-router 5.1 版本中,有一个名为 useLocation 的钩子,它返回当前位置对象.这在您需要知道当前 URL 的任何时候都可能有用.
In the 5.1 release of react-router there is a hook called useLocation, which returns the current location object. This might useful any time you need to know the current URL.
import { useLocation } from 'react-router-dom'
function HeaderView() {
const location = useLocation();
console.log(location.pathname);
return <span>Path : {location.pathname}</span>
}
这篇关于React Router v4 - 如何获取当前路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文