简体   繁体   English

为什么要在 React 路由中传递 {...props}?

[英]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我知道 {...props} 表示多个参数,但我不明白为什么我需要它,因为下面的代码也工作得很好,并且 props.msg 在测试中可用

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

So what does {...props} actually do when passed in during render?那么 {...props} 在渲染过程中传入时实际上做了什么?

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.如果Test没有使用这些中的任何一个,那么您不必通过它们。

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.请记住,您可以在路由中使用参数,例如:/users/:username 这些道具将允许您访问它。 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 https://reacttraining.com/react-router/web/api/Route/route-props

more doc about the 3 props that are provided :有关提供的 3 个道具的更多文档:

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

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