【问题标题】:How to implement authenticated routes in React / Ant Design Pro如何在 React / Ant Design Pro 中实现经过身份验证的路由
【发布时间】:2019-10-26 18:26:26
【问题描述】:

我希望能够表演:

router.push('/compose')

如果未登录用户将被重定向到登录页面并从那里转到 /compose。 我很乐意学习通用的 React 解决方案或特定的 Ant Design Pro 解决方案。 我知道 And Design Pro 有 AuthorizedRoute 但我不知道它是否允许这样做。

我正在使用 react-router 4.3.1 和 antd 3.23.6。

谢谢

编辑:

它可能需要类似于@tyler-mcginnin answer:

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

【问题讨论】:

    标签: reactjs authentication react-router antd ant-design-pro


    【解决方案1】:

    我使用 React-router,然后使用条件来做到这一点。如果我有一个 isAuthenticated 变量,设置为 true 或 false,传递给 props,它看起来像这样:

        let routes = (//unauthenticated routes
            <Switch>
                <Route path = "/auth" component = {Auth} />
                <Redirect to = "/auth" />
            </Switch>
        )
    
        if(props.isAuthenticated){ //authenticated routes
            routes  = (
                <Switch>
                    <Route path = "/manager" component = {DataManager} />
                    <Route path = "/logout" component = {Logout} />
                    <Redirect to = "/visualiser" />
                </Switch>
            )
        }
    

    基于 cmets 的更新:

    然后在您的 auth 组件中创建一个设置 authRediect 变量的变量,然后在您的 JSX 中呈现它。像这样的:

        // This sets up a <Redirect> component so that if the state isAuthenticated is true it will not show the /auth page and isntead will redirect to the desired component:
        let authRedirect = null;
        if (props.isAuthenticated) {
            authRedirect = <Redirect to = "/visualiser" />
        };
    ...
    
        return(
                <React.Fragment>
                        {/*The line below performs an auth redirect if the user is authenticated*/}
                        {authRedirect}
                        <h1>Welcome </h1>
                </React.Fragment>
        );
    

    因此,基本上您只需根据您的状态是否设置为已验证状态,有条件地返回 authRedirect 变量。

    【讨论】:

    • 我不想在其中添加太多代码,但如果您需要更多上下文,请告诉我,我可以完善它。
    • 感谢@Snek,登录后我还需要它重定向到目标组件
    • 嗨@kambi,一旦您登录,您的身份验证状态将发生变化,这将导致重新渲染。这意味着 if(props.isAuthenticated) 将再次运行,因此将发生 switch 块底部的重定向。这有帮助吗?
    • 嗨@Snek,谢谢,我知道重新渲染会在登录后显示路由器,但我希望它在登录后自动将我重定向到那里
    • 啊,我知道差距在哪里了。我已经更新了我的答案。基本上,您只需要创建一个经过身份验证的视图,然后根据您的身份验证状态进行渲染。
    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2019-10-22
    • 2017-09-11
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多