gpt4 book ai didi

javascript - 如何在 React 中正确处理非 PrivateRoutes?

转载 作者:行者123 更新时间:2023-11-30 20:20:35 25 4
gpt4 key购买 nike

我的 app.js 中有这段代码,并配置了一个 PrivateRoute,它要求用户登录,并且只有在设置了 cookie 时才允许访问。但是,我想限制用户在成功登录后尝试点击 /login 。我使用了 PrivateRoute 的反向逻辑并创建了用于此目的的 LoginRoute 但想知道是否有更好的方法。

import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'
import cookies from 'cookies-js';

import Home from './homeComponent';
import Login from './loginComponent';
import Dashboard from './dashboardComponent';
import NoMatch from './noMatchComponent';

const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<LoginRoute path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
);
};

const LoginRoute = ({ component: Component, rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Redirect to={{
pathname: '/dashboard',
state: { from: props.location }
}} />
: <Component {...props} />
)} />
)

const PrivateRoute = ({ component: Component, rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
)

export default App;

最佳答案

有几种方法可以处理私有(private)路由,其中​​一种方法是按照您编写的方式编写自定义登录路由,以防止用户访问 /login 如果他/她已经登录。您需要在 route 进行的唯一更正是正确使用 rest 语法

const LoginRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Redirect to={{
pathname: '/dashboard',
state: { from: props.location }
}} />
: <Component {...props} />
)} />
)

和私有(private)路由

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
)

处理此问题的另一种方法是身份验证 HOC。

const RequireAuth = (Component) => { 

return class App extends Component {

render() {
const { location } = this.props;
if (cookies.get('access-token')) {
if(location.pathname === '/login') {
return <Redirect to={'/dashboard'} />
}
return <Component {...this.props} />
}
return <Redirect to="/login"/>
}
}

}

export { RequireAuth }

你会像这样使用它

const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/login" component={RequireAuth(Login)} />
<Route path="/dashboard" component={RequireAuth(Dashboard)} />
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
);
};

关于javascript - 如何在 React 中正确处理非 PrivateRoutes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51491736/

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