如何使用 react-router 使用私有路由? [英] How to use Private Route using react-router?
本文介绍了如何使用 react-router 使用私有路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用身份验证建立安全路由.我已经在 App.jsx 文件中定义了路由.我正在使用路由"来定义要呈现的组件.
I want to make secure routes using authentication. I have defined the routes in App.jsx file. I am using "Route" to define which component to render.
在 App.jsx 中
In App.jsx
<Route
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>
上面的代码没有任何问题.我想让它像下面一样安全.
The above code works without any issue. I want to make that secured like below.
<PrivateRoute
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user}
handleChildFunc={this.handleChildFunc}/>}
/>
<小时>
在 PrivateRoute.jsx 中
In 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" />
}
}
如果令牌存在,则渲染一个组件.否则,重定向到/login.
If the token is present, render a component. Otherwise, redirect to /login.
推荐答案
你可以让你的 PrivateRoute
喜欢,
You can have your PrivateRoute
like,
<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' />
)}
/>
}
这篇关于如何使用 react-router 使用私有路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文