简体   繁体   中英

React Router access params from another component

I am currently looking into React.js & Redux and was playing around with react-router. My question is: Is there a way to access url params from another Component?

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. With ReactRouterDOM.withRouter I can get access to props.match . The Problem is that this is not the same as in the Foo Component (it contains the information about the parent route '/'). So how do I get the value in the Header Component and am I even on the right track?

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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