如何在React / Ant Design Pro中实现经过身份验证的路由

时间:2019-10-26 18:26:26

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

我希望能够执行:

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}}} />}
    />
  )
}

1 个答案:

答案 0 :(得分:0)

我使用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>
        )
    }

根据评论进行更新:

然后在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变量。