How does react-router pass params to other components via props?

人走茶凉 提交于 2019-11-28 18:39:37

That is a question about react-router internals.

react-router is a React component itself and it uses props to pass all the routing information to the children components recursively. However, that is an implementation detail of react-router and i understand it can be confusing, so read on for more details.

The routing declaration in your example is:

<Router history={new HashHistory}>
  <Route path="/" component={Main}>
    <Route path = "topics/:id" component={Topic}></Route>
  </Route>
</Router>

So basically, React-Router will go through each of the components in the routing declaration (Main, Topic) and "pass" the following props to each of the components when the component is created using the React.createElement method. Here are all the props passed to each component:

const props = {
   history,
   location,
   params,
   route,
   routeParams,
   routes
}

The props values are computed by different parts of react-router using various mechanisms (e.g. extracting data from the URL string using regex expressions).

The React.createElement method itself allows react-router to create an element and pass the props above. The signature of the method:

ReactElement createElement(
  string/ReactClass type,
  [object props],
  [children ...]
)

So basically the call in the internal implementation looks like:

this.createElement(components[key], props)

Which means that react-router used the props defined above to initiate each of the elements (Main, Topic etc.), so that explains how you could access this.props.params in the Topic components itself, it was passed by react-router!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!