gpt4 book ai didi

reactjs - 使用 React-Router-Dom 创建 PrivateRoute

转载 作者:行者123 更新时间:2023-12-04 15:25:14 24 4
gpt4 key购买 nike

我见过很多关于人们如何使用 react-router-dom 创建私有(private)路由的用例。它通常看起来像这样:

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'}
/>

关于reactjs - 使用 React-Router-Dom 创建 PrivateRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62396844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com