Javascript 反应保护路由
我有以下代码:Javascript 反应保护路由,javascript,reactjs,Javascript,Reactjs,我有以下代码: const PrivateRoute = ({ component: Component, ...rest }) => { return (<Route {...rest} render={(props) => (isAuthenticated() === true ? <Component {...props} /> : <Redirect to='/login' /> )} />) } const PrivateRoute
const PrivateRoute = ({ component: Component, ...rest }) => {
return (<Route {...rest} render={(props) => (isAuthenticated() === true ? <Component {...props} /> : <Redirect to='/login' /> )} />)
}
const PrivateRoute=({component:component,…rest})=>{
返回((isAuthenticated()==true?:)}/>)
}
但是我不明白这是怎么回事。。我称之为:
<PrivateRoute exact path = '/home' component={Home}></PrivateRoute>
这很有效,我就是不明白。道具在哪里传递?什么是组件:组件
如果有人能解释一下这些组件是如何工作的,我将不胜感激。
组件:组件
是
您可以按以下方式重新编写:
const PrivateRoute = (props) => {
const Component = props.component;
//shallow copy props, can also do {...props}
const rest = Object.assign({},props);
//delete component property from rest
// this will not affect props becaus of the shallow copy
react router Route组件将获取一个props.component,并使用传递到Route的所有props减去props.component来渲染该组件
您创建一个
privaterout
,它执行相同的操作,但不是直接渲染传递到道具中的组件,而是渲染路由并向其传递一个渲染道具,该渲染道具是动态创建的组件()=>jsx
。Route将为您呈现此组件。组件:组件
您可以按以下方式重新编写:
const PrivateRoute = (props) => {
const Component = props.component;
//shallow copy props, can also do {...props}
const rest = Object.assign({},props);
//delete component property from rest
// this will not affect props becaus of the shallow copy
react router Route组件将获取一个props.component,并使用传递到Route的所有props减去props.component来渲染该组件
您创建一个
privaterout
,它执行相同的操作,但不是直接渲染传递到道具中的组件,而是渲染路由并向其传递一个渲染道具,该渲染道具是动态创建的组件()=>jsx
。Route将为您呈现此组件。您将在Route
中的render
参数中传递组件。因此,如果您的isAuthenticated
方法返回true,则render
将提供您传递的任何组件,否则它将获得重定向
组件,从而重定向用户登录。如果您将任何其他道具传递给PrivateRoute
,这些道具将使用rest参数()传递给路由
组件。您将在路由
中的渲染
参数中传递组件。因此,如果您的isAuthenticated
方法返回true,则render
将提供您传递的任何组件,否则它将获得重定向
组件,从而重定向用户登录。如果您将任何其他道具传递给PrivateRoute
,则这些道具将使用rest参数()传递给Route
组件。