【问题标题】:React Router Redirect not working in Private Route反应路由器重定向在私有路由中不起作用
【发布时间】:2020-02-05 18:33:23
【问题描述】:

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

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>

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

我已尝试仅返回 te Private 路由中的重定向以强制重定向并检查它是否符合我的身份验证。但是无论它包含在哪里,重定向似乎都不起作用。

【问题讨论】:

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


    【解决方案1】:

    你不需要路线

    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);
    

    【讨论】:

    • 但是路由正在传递道具现在它只是说道具没有定义
    • 重定向中的 props.location 呢?
    • 我改变了答案。我使用班级形式。
    猜你喜欢
    • 2017-09-17
    • 2020-10-22
    • 2019-10-03
    • 2020-11-12
    • 2019-01-19
    • 2016-11-27
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多