gpt4 book ai didi

reactjs - 如何使用 react-router 使用 Private Route?

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

我想使用身份验证制作安全路由。我已经在 App.jsx 文件中定义了路由。我正在使用“Route”来定义要渲染的组件。

在 App.jsx 中

<Route 
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>

上面的代码没有任何问题。我想让它像下面一样安全。
<PrivateRoute 
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>

在 PrivateRoute.jsx
const PrivateRoute = ( props ) => {
const user = "token from cookie"; // i will fetch token stored in cookie
if(user !== null) {
return <Route />;
}
else {
return <Redirect to="login" />
}
}

如果 token 存在,则渲染一个组件。否则,重定向到/login。

最佳答案

你可以有你的PrivateRoute像,

<PrivateRoute 
path='/dashboard'
exact={true}
component={Dashboard}
handleChildFunc={this.handleChildFunc}
/>
const PrivateRoute = ({ component: Component, handleChildFunc, ...rest }) => {
const user = "token from cookie";
return <Route {...rest} render={(props) => (
user !== null
? <Component {...props} user={user} handleChildFunc={handleChildFunc}/>
: <Redirect to='/login' />
)}
/>
}

关于reactjs - 如何使用 react-router 使用 Private Route?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57660849/

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