gpt4 book ai didi

javascript - 当登录用户为 false 时,React 中的 PrivateRoute 不会重定向

转载 作者:行者123 更新时间:2023-11-28 03:19:33 26 4
gpt4 key购买 nike

我试图在我的应用程序中实现一些安全性,并最终创建了以下代码:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const PrivateRoute = ({
component: Component,
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to='/auth/login' />
) : (
<Component {...props} />
)
}
/>
);

PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
auth: state.auth
});

export default connect(mapStateToProps)(PrivateRoute);

auth 来 self 的状态管理,从 Chrome 浏览器上安装的 Redux Devtools 中查看时,它看起来与此完全相同;这是:

redux devtools console

当用户登录时,

isAuthenticatedloading 通常为 true;效果很好。我遇到的问题是,当没有人登录时,我的 PrivateRoute 不会重定向到 auth/login 页面。有谁知道如何解决这个问题?这是我需要 PrivateRoute 组件的路由之一的示例:

<PrivateRoute exact path='/edit-basics' component={EditBasics} />

上面的路由是一个编辑当前登录用户信息的页面,仅供他/她使用。我仍然可以在未登录的情况下访问它。

最佳答案

因此,您可能会因 && 而遇到错误运算符以及您传递给 render 的三元运算内的两个表达式方法Route

您必须找到一种不同的方法来验证它是否仍在加载。

在 JSX 中,如果您配对 true && expression它的计算结果为 expression – 所以基本上你会返回 !loading作为渲染组件。

了解更多:https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator

const PrivateRoute = ({
component: Component,
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>

// TWO OPERATIONS WITH && WILL CAUSE ERROR
!isAuthenticated && !loading ? (

<Redirect to='/auth/login' />
) : (
<Component {...props} />
)
}
/>
);



另外,

React Router 的作者建议使用子组件构建这种私有(private)路由,而不是将组件作为 prop 传递给渲染。

了解更多:https://reacttraining.com/react-router/web/example/auth-workflow

function PrivateRoute({ auth, children, ...rest }) {
return (
<Route
{...rest}
render={() =>
!auth.isAuthenticated ? (
<Redirect
to={{
pathname: "/auth/login",
state: { from: location }
}}
/>
) : (
children
)
}
/>
);
}

并调用该路由:

<PrivateRoute path="/protected" auth={auth} >
<ProtectedPage customProp="some-prop" />
</PrivateRoute>

关于javascript - 当登录用户为 false 时,React 中的 PrivateRoute 不会重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290919/

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