为什么我应该在React路由中使用扩展运算符?

huangapple go评论125阅读模式
英文:

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 属性?

这样,任何 其他 属性都会被传递,比如 foobar

> 在 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).

huangapple
  • 本文由 发表于 2020年1月6日 23:21:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定