简体   繁体   English

使用 React-Router-Dom 创建 PrivateRoute

[英]Create PrivateRoute with React-Router-Dom

I have seen lots of use cases about how people create private route with react-router-dom.我已经看到很多关于人们如何使用 react-router-dom 创建私有路由的用例。 It usually looks like this:它通常看起来像这样:

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest}) =>  (
    <Route {...rest} render={props => (
        isAuthenticated ?
            <Component {...props} />
        : <Redirect to="/signin" />
    )} />
);

And my question is: If I can use this way to do the same thing?我的问题是:如果我可以用这种方式做同样的事情?

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
    isAuthenticated ? <Route {...rest} render={props => <Component {...props}/>}/> :<Redirect to="/signin" />
)

It seems working when I ran the code.当我运行代码时它似乎工作。 But I still want to know why we do the condition check at the first way of writing?但是我还是想知道为什么我们在第一种写法的时候做条件检查? Is the second way of writing incorrect?第二种写法不正确吗? If so, why?如果是这样,为什么? Thank you!谢谢!

It's just a preference thing, either is fine and both will work.这只是一个偏好的事情,两者都可以,两者都可以。 you can also make it even shorter and more readable like this if you like如果你愿意,你也可以像这样使它更短、更易读

const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
    isAuthenticated ? <Component {...rest} /> : <Redirect to="/signin" />
)

and then render like so:然后像这样渲染:

<PrivateRoute
   exact
   component={ComponentToRender}
   path="/path"
   aProp={'aProp'}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM