[英]What's ES6 magic is happening in this React Component?
我正在關注本教程https://serverless-stack.com/ ,我在https://serverless-stack.com/chapters/create-a-route-that-redirects.html
這引入了AuthenticatedRoute
,它檢查名為isAuthenticated
的prop的值,以決定是否天氣呈現組件或重定向用戶login
import React from "react";
import { Route, Redirect } from "react-router-dom";
export default ({ component: C, props: cProps, ...rest }) =>
<Route
{...rest}
render={props =>
cProps.isAuthenticated
? <C {...props} {...cProps} />
: <Redirect
to={`/login?redirect=${props.location.pathname}${props.location
.search}`}
/>}
/>;
我得到了它所取得的成就,但我不確定它是如何做到的。
有人可以向我解釋下面有什么問題嗎?
component: C
...rest
<C {...props} {...cProps} />
AuthenticatedRoute
是一個功能 (無狀態)組件 - 一個功能。
使用props作為第一個參數調用該組件,並且該行({ component: C, props: cProps, ...rest })
解構道具,並將其中一些分配給變量。 component: C
從props對象中提取component
屬性,並將其分配給變量C
...rest
({ component: C, props: cProps, ...rest })
是ECMAScript的Object Rest / Spread Properties提議的一部分 ,你需要babel的Object rest spread變換才能在當前的瀏覽器中工作。 它從未分配給變量的所有對象屬性(其余)創建一個新對象。
<C {...props} {...cProps} />
是react的JSX spread屬性 ,它將所有對象( props
和cProps
)屬性轉換為組件屬性(如寫入key = value)。 cProps
的props
將覆蓋props
的屬性,因為它們出現在props
之后。
component:C - 在ES6中,如果未傳遞參數,則可以進行默認初始化。 這里的組件將默認為C.
...休息 - 使用ES6,您可以傳播數據結構的元素。 這里休息可以有渲染功能的路徑路徑。
- cprops和props的每個元素都作為屬性傳遞給C組件。 cProps中的道具將覆蓋道具后面出現的道具屬性。
在這種情況下, Authenticated Route
被稱為High Order Component。 Authenticated Route
包裹Route
組件並有條件地返回component: C
如果用戶已通過身份驗證,則為component: C
或Redirect
組件。
component
是Authenticated Route
一個簡單的道具,但它重命名為C
,因為反應組件必須大寫。 props: cProps
它想要接收到組件的道具 props
其一個Route
渲染需要被應用到組件道具,其中所述渲染方法應該返回 ...rest
它包含任何其他道具的物體,基本上是指Route
然后你可以簡單地使用<AuthenticatedRoute />
包裝並根據上面寫的信息傳遞你需要的道具
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.