英文:
Why should I use the spread operator in React Route?
问题
The instructor uses {...props}
inside the route to pass all the props received by the route component down to the User
component. This is done to ensure that any additional props received by the Route
component are also available within the User
component.
In the User.js
file, the code this.props.getUser(this.props.match.params.login)
is used to call the getUser
function with the login
parameter extracted from the route's match object. This allows the User
component to fetch user data based on the login
parameter from the URL.
So, using {...props}
in the route and passing this.props.match.params.login
to getUser
are related, as they ensure that the necessary props and data are available for the User
component to function correctly.
英文:
So I am watching a tutorial where instructor uses {...props} inside a route. Why would he use it if he is already passing user and getUser props?:
<Route exact path="/user/:login" render={props => (
<User {...props} getUser={this.getUser} user={user} />
)}
/>
Btw, In the User.js, where those props are being passed to, he uses:
this.props.getUser(this.props.match.params.login). Is it possible it has something to do with this?
答案1
得分: 3
> 为什么他要使用它,如果他已经传递了 user 和 getUser 属性?
这样,任何 其他 属性都会被传递,比如 foo
和 bar
。
> 在 User.js 中,他将这些属性传递给了它,他使用的是:this.props.getUser(this.props.match.params.login)。这可能与这有关吗?
不。正如你所说,他明确提供了该属性,而不是通过扩展传递。通过在扩展之后这样做,他确保了他明确版本的使用(无论你是否将一个 getUser
传递给容器的属性,它都不会被使用,因为他的 getUser
会覆盖它;同样适用于 user
)。
英文:
> Why would he use it if he is alreading passing user and getUser props?
So that any other props get passed like, like foo
and bar
.
> In the User.js, where those props are being passed to, he uses: this.props.getUser(this.props.match.params.login). Is it possible it has something to do with this?
No. As you said, he's supplying that prop explicitly, not via spread. And by doing so after the spread, he's ensuring that his explicit version is used (it doesn't matter whether you pass a getUser
to the container's props, it won't get used because his getUser
overrides it; same with user
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论