我已经看到了很多用例,说明人们如何使用react-router-dom创建专用路由。通常看起来像这样:
const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest}) => (
<Route {...rest} render={props => (
isAuthenticated ?
<Component {...props} />
: <Redirect to="/signin" />
)} />
);
我的问题是:是否可以使用这种方式来做同样的事情?
const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
isAuthenticated ? <Route {...rest} render={props => <Component {...props}/>}/> :<Redirect to="/signin" />
)
当我运行代码时,它似乎正常工作。但是我仍然想知道为什么我们在第一种书写方式下进行条件检查?第二种写作方式不正确吗?如果是这样,为什么?谢谢!
这只是一个喜好,两者都可以并且都可以。您也可以像这样使它更短,更易读
const PrivateRoute = ({component: Component, auth:{ isAuthenticated }, ...rest }) => (
isAuthenticated ? <Component {...rest} /> : <Redirect to="/signin" />
)
然后像这样渲染:
<PrivateRoute
exact
component={ComponentToRender}
path="/path"
aProp={'aProp'}
/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句