简体   繁体   中英

Passing state to react-router 1.x

In react-router version 0.13.3 I have

Router.run(routes, createBrowserHistory, function(Handler, state) {
    React.render(<Handler query={ state } path={ state.pathname }/>, document.getElementById('app'))
});

In react-router 1.0.0.rc3 I have

let history = createBrowserHistory();
React.render(<Router history={ history } >{ routes }</Router>, document.getElementById('app'));

With react-router 0.13.3, I was able to pass state to my Components with a callback. I was wondering how I can do the same with version react-router 1.x ?

React Router 1.0 now creates elements from your route components, passing them the following routing-related state as props by default:

  • history - a History object
  • location - a Location object
  • params - parameters extracted from the URL
  • route - the route object the rendered component belongs to
  • routeParams - parameters extracted from the URL for the route object the rendered component belongs to
  • routes - an array of all the route objects which were matched

You should be able to use these to get a hold of routing-related state, eg to get the pathname, you could use this.props.location.pathname inside a route component, or pass these onto children which need them.

The 1.0 upgrade guide has more details about this .


If you want to pass additional props to an individual route component when rendering it, you can use React.cloneElement() like so:

{React.cloneElement(this.props.children, {extra: 'extra prop'})

If you want to pass additional props when a route component element is being created, you can pass a custom createElement() function to <Router> .

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