简体   繁体   中英

Why pass {...props} in a React Route?

I'm using the route below just because it was the code I found on the web:

<Route exact path="/test" render={(props) => <Test {...props} msg={ "abc" } /> } />

I know the {...props} denotes multiple arguments but I can't understand why I need it at all because the code below also works just fine and props.msg is available in Test expected

<Route exact path="/test" render={() => <Test msg={ "abc" } /> } />

So what does {...props} actually do when passed in during render?

From the documentation :

The render prop function has access to all the same route props (match, location and history) as the component render prop.

If Test is not using any of these then you don't have to pass them.

For your use case, your second code snippet is sufficient and will work just fine.

Spreading the props into the child component like

<Route exact path="/test" render={(props) => <Test {...props} msg={ "abc" } /> } />

makes sense if you want to pass properties to the child component that you are not handling yourself but receiving from another source like the Route-Component itself (in particular the route props "match", "location" and "history").

Keep in mind you can have parameters in your route, ex: /users/:username Those props will allow you to access it. In your case, you probably don't need it but you're better to always include them so it's consistent.

https://reacttraining.com/react-router/web/api/Route/route-props

more doc about the 3 props that are provided :

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