简体   繁体   English

来自其他组件的React Router访问参数

[英]React Router access params from another component

I am currently looking into React.js & Redux and was playing around with react-router. 我目前正在研究React.js和Redux,并且正在使用react-router。 My question is: Is there a way to access url params from another Component? 我的问题是:有没有办法从另一个组件访问URL参数?

For example: 例如:

I have a Foo component which displays the :bar param (via props.match.params.bar ), but I also want to display the value of :bar in the Header Component. 我有一个Foo组件,它显示:bar参数(通过props.match.params.bar ),但我也想在Header组件中显示:bar的值。 With ReactRouterDOM.withRouter I can get access to props.match . 使用ReactRouterDOM.withRouter我可以访问props.match The Problem is that this is not the same as in the Foo Component (it contains the information about the parent route '/'). 问题在于这与Foo组件中的不同(它包含有关父路由“ /”的信息)。 So how do I get the value in the Header Component and am I even on the right track? 那么,如何在Header Component中获取值,我是否走在正确的轨道上?

Thanks in advance 提前致谢

 const Foo = (props) => { return (<div> <h1> Foo {props.match.params.bar} </h1> </div>); }; const App = (props) => { return ( <div> <HeaderWrapper /> <h1> Hello App </h1> <p><ReactRouterDOM.Link to='/foo/bar'>Foo Bar</ReactRouterDOM.Link></p> <hr /> <ReactRouterDOM.Route path='/foo/:bar' component={Foo} /> </div>); }; // Header const Header = (props) => { console.log(props); return ( <header> <small>You are here: {}</small> </header>); }; const HeaderWrapper = ReactRouterDOM.withRouter(Header); // Router ReactDOM.render(( <ReactRouterDOM.MemoryRouter> <ReactRouterDOM.Route path='/' component={App} /> </ReactRouterDOM.MemoryRouter > ), document.getElementById('root')); 
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script> <script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script> 

As far as I know, react-router doesn't have any standard way to achieve what you need. 据我所知,react-router没有任何标准的方法来实现您所需要的。 But you can use regular expression with path-to-regexp library to do that manually. 但是您可以将正则表达式与正则表达式路径库一起使用来手动执行此操作。 You will always get the correct result as react-router it self internally use this library to match routes. 您将始终获得正确的结果,因为react-router本身在内部使用此库来匹配路由。

const re = pathToRegexp('/foo/:bar')
const result = re.exec(props.location.pathname)
if(result){
    console.log(result[1]); //bar
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM