我已经看到了很多关于人们如何使用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'}
/>