React Router Redirect在专用路由中不起作用

时间:2019-10-08 13:02:25

标签: reactjs redirect react-router react-router-v4 react-router-dom

我有这个专用路由组件,仅当用户登录时才用于呈现组件,否则应重定向到登录页面。

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

export default withRouter(PrivateRoute);

这是我的主要应用程序:

            <BrowserRouter>
                <div className="wrapper">
                    <Switch>
                        <Route path="/login" component={LoginPage} />
                        <> 
                        <div className="dashboard">
                            <SideBar />
                            {permittedEvents &&
                                <div className="content-area">
                                    <PrivateRoute exact path="/" component={Dashboard} />
                                    <PrivateRoute exact path="/calendar" component={Calendar} />
                                </div>
                            }
                        </div>
                        </>
                    </Switch>
                </div>
            </BrowserRouter>

由于某种原因,重定向将被完全忽略,并且当用户未登录时,将显示侧边栏,但不会显示内容或登录页面。

我尝试仅在专用路由中返回重定向以强制进行重定向,并检查是否通过我的身份验证。但是,无论重定向包含在何处,重定向都似乎无效。

1 个答案:

答案 0 :(得分:2)

您不需要路线

class PrivateRoute extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { component: Component, ...rest } = this.props;

        const redirectPath = (<Redirect to={{
            pathname: "/login",
            state: {
                from: this.props.location.pathname
            }
        }}/>);

   if (!ok) {
                return redirectPath;
            }
        return <Component {...this.props} />;
    }
};

export default  withRouter(PrivateRoute);