javascript - 对 React PrivateRoute 语法 {} 感到困惑

标签 javascript reactjs ecmascript-6 react-router-v4

我是 React 新手。我现在正在研究react router,看到很多人使用PrivateRoute组件来处理用户身份验证页面。但是,我对这个函数的语法和理解感到非常困惑。

export function PrivateRoute({ component: Component, authed, ...rest }) {
 return (
    <Route {...rest}
        render={
            (props) => authed ? <Component {...props} /> : <Redirect to={{ pathname: 'login', state: { from: props.location } }} />
        }
    />
 )
}

其用法如下

< PrivateRoute authed={this.props.isAuthenticated} path="/profile" component={MyProfile} />

我可以知道为什么我们将所有参数包装在 {} 中,就像这样 { component: Component, authed, ...rest } 吗?
为什么我们这样使用“组件:组件”?是用于中断组件={MyProfile} 吗?但我们为什么要这样写呢? (props) 和 ...props 是什么?

...剩下的就是 path="/profile"和其他参数,例如“精确”,对吗?

非常感谢!

最佳答案

May I know why we wrap all the parameters inside {} like this { component: Component, authed, ...rest }?

这是一种称为解构赋值的 JavaScript 语法。这是从数组和对象中解压值的一种非常方便的方法。

假设您的函数需要一个带有 id 键的对象。您编写 function(myObject) { return myObject.id; }。通过解构,您可以编写 function({id}) { return id; }。并期望传递的对象将被解构为请求的键。

what are the (props) and ...props?

首先,已知...是扩展运算符。这是另一个方便的快捷方式,可以将数组或对象扩展到需要参数或元素的位置。

其次,(props) 是箭头函数声明的一部分。请注意,它后面跟着一个箭头: (props) => 。这与编写function(props)相同。然而,箭头函数和 function 关键字之间有一些细微的区别,主要是 this 关键字所指的内容。

另请注意,(props) => 后面跟着一个隐式返回。您可以使用显式返回来编写像这样的箭头函数 (props) => { return true;}。或者不带括号的隐式返回,如下所示:(props) => true

关于javascript - 对 React PrivateRoute 语法 {} 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55522413/

相关文章:

javascript - React,单击时获取列表索引

javascript - 如何在 Date Picker jquery-ui 中更改 div 中的这个特定的 css 类?

reactjs - 如何在ReactJs应用程序中使用reduce()代替传统的foreach循环

javascript - 重定向到新页面提交 : this. props.history.push

mysql - 使用 React.js 和 Express 删除发布到 MySQL 的帖子

javascript - 如何在es6中过滤嵌套对象并返回父对象

javascript - 如何在 react js 中动态更改网站的标题(也在源代码中)?

javascript - Ajax,只发送值不显示页面

javascript - drawImage - 调整大小并保持比例

javascript - "Calling an asynchronous function without callback is deprecated."但是有回调