gpt4 book ai didi

javascript - React Router 重定向速度很慢

转载 作者:行者123 更新时间:2023-12-05 08:08:29 25 4
gpt4 key购买 nike

我正在使用高阶组件 (PublicRoute) 来根据用户是否经过身份验证有条件地呈现另一个组件。我制作了另一个高阶组件 PrivateRoute,以达到相反的效果。思路是不希望登录的用户能够访问登录页面,也不希望未登录的用户查看其他页面。 (实际上,这不太可能,除非他们手动输入 URL,但我仍然想确保它不会发生。)

问题是 Redirect 组件仅在 Login 组件呈现几秒钟后才起作用。这似乎是一种奇怪的行为。状态的 auth 部分包含一个对象或者是 false 或 null(null 是默认状态)。所以应该没有问题。 PrivateRoute 也会出现同样的问题(例如,未经身份验证的用户仍然可以访问购物车页面)。

公共(public)路由.js

export const PublicRoute = ({ 
isAuthenticated,
component: Component,
...rest
}) => (
<Route
{...rest}
component={(props) => (!isAuthenticated ? (
<div>
<Component {...props}/>
</div>
) : ( <Redirect to="/shop"/> )
)}/>
);

const mapStateToProps = ({ auth }) => ({ isAuthenticated: !!auth });

export default connect(mapStateToProps)(PublicRoute);

AppRouter.js

  <PublicRoute path="/login" component={Login}/>

最佳答案

我使用的模式是我使用 render <Route ... /> 的方法,像这样:

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

const ProtectedRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/my-login-page",
state: { from: props.location }
}}
/>
)
}
/>
);

ProtectedRoute.propTypes = {
component: PropTypes.func,
location: PropTypes.object,
isAuthenticated: PropTypes.bool
};

export default ProtectedRoute;

并使用连接方法将其连接到我的 Redux 状态:

import { connect } from "react-redux";
import { withRouter } from "react-router";

import ProtectedRoute from "components/shared/ProtectedRoute";

export default withRouter(
connect(state => ({
isAuthenticated: true // logic for verifying
}))(ProtectedRoute)
);

然后使用 ProtectedRoute作为 protected 路由的路由组件 - 否则只需使用常规 Route .

关于javascript - React Router 重定向速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863491/

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