简体   繁体   中英

Create PrivateRoute with React-Router-Dom

I have seen lots of use cases about how people create private route with 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'}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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