登录重定向后如何重定向到任何URL?

时间:2019-10-17 19:39:56

标签: javascript reactjs

我想将用户重定向到他登录后输入的任何URL 例如;我的用户在浏览器中输入http://localhost:3000/login/tickets, 如果他还没有登录,我将需要该程序来加载登录页面,登录后,该程序将重定向到该页面,我可以在单个页面上执行该操作,但是我希望它是动态的,就像这样。 >

    isAuthenticated()
      ? (
        <Component {...props} />
        ) : <Redirect to=`/login?next=${this.props.location.search}` />
      )}

此重定向很快将使用下一个标记加载登录页面

5 个答案:

答案 0 :(得分:1)

您需要通过获取变量来更新状态,并应用检查是否更改过的状态,如果是,则重定向到所需的页面,如果不返回。由于您尚未发布完整的代码。您可以参考此视频以更广泛,更清楚地了解以下内容: https://www.youtube.com/watch?v=zSt5G3s3OJI

答案 1 :(得分:1)

我的解决方案是按照您的描述做。如果要求用户登录,我做了一个HOC来包装我的路线的组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter, Redirect } from 'react-router-dom';

/**
 * Higher-order component (HOC) to wrap restricted pages
 */
export default function LoggedInOnly(BaseComponent) {
    class Restricted extends Component {
        state = {};
        static getDerivedStateFromProps(nextProps) {
            const { history, location } = nextProps;
            if (!nextProps.isLoggedIn) {
                history.replace({ pathname: '/signin', search: `dest=${encodeURIComponent(location.pathname)}` });
            }
            return null;
        }
        render() {
            const { location, staticContext } = this.props;

            if (this.props.isLoggedIn) return <BaseComponent {...this.props} />;

            const destinationURL = `/signin?dest=${encodeURIComponent(location.pathname)}`;
            if (staticContext) staticContext.url = destinationURL;

            return <Redirect to={destinationURL} />;
        }
    }

    const mapStateToProps = state => ({
        isLoggedIn: !!state.globalUserState.loggedInUserEmail,
    });

    return withRouter(connect(mapStateToProps)(Restricted));
}

在我的情况下,我还在静态上下文上设置了url,因此我可以在服务器端渲染中适当地处理重定向。如果您不这样做,则可以忽略该部分。

不过,要使用它,我会在SSR渲染函数之后重定向,如下所示:

if (context.url) {
    console.log(`Redirecting to URL ${context.url}`);
    return res.redirect(context.url);
}

使用此路线的路线如下:

<Route path="/preferences" component={LoggedInOnly(SettingsView)} />

在登录页面上,我抓住url参数来查看是否有目的地。如果存在,我将在登录成功后重定向到那里。

我使用查询字符串和位置的搜索组件来执行此操作:

const { destination } = queryString.parse(props.location.search);

以上假设您正在使用withRouter在道具中获取位置信息。

在客户端身份验证成功后,我将直接重定向到目标(如果存在)

window.location.href = this.props.destination;

您还可以使用history.push或类似方法来完成上述操作。

就我而言,如您所见,我正在使用redux来跟踪已登录的用户状态。

答案 2 :(得分:0)

您可以通过执行以下操作来完成所需的操作:

if(isAuthenticated)
  this.props.history.push('/login', {lastPage: this.props.location.match})

用户登录后,您无法将其重定向到传递的参数lastPage

另一种方法是将lastPage存储在redux中,并在用户登录后对其进行访问。

答案 3 :(得分:0)

我遇到了同样的问题,我做了一个HOC来解决它。

import React from "react";
import { connect } from "react-redux";
import Login from "../../Auth/Login";
import { withRouter } from "react-router-dom";
import qs from "querystring";

const signInPath = "/signin";
const signUpPath = "/signup";
const forgotPassPath = "/forgot";
const resetPassPath = "/resetpassword";
const returlUrlPath = "returnUrl";

const allowedPaths = pathname =>
  pathname === signInPath ||
  pathname === signUpPath ||
  pathname === forgotPassPath ||
  pathname === resetPassPath;

const homePath = "/";

export default Component => {
  class AuthComponent extends React.Component {
    componentDidMount() {
      this.checkAuthentication();
    }

    componentDidUpdate(nextProps) {
      if (
        nextProps.location.pathname !== this.props.location.pathname ||
        this.props.loggedIn !== nextProps.loggedIn
      ) {
        this.checkAuthentication();
      }
    }

    checkAuthentication() {
      const {
        loggedIn,
        history,
        location: { pathname, search }
      } = this.props;
      if (!loggedIn) {
        if (!allowedPaths(pathname)) {
          const returlUrl =
            pathname.length > 1
              ? `${returlUrlPath}=${pathname.replace("/", "")}`
              : undefined;
          history.replace({ pathname: signInPath, search: returlUrl });
        }
      } else if (search) {
        const parsedSearch = qs.parse(search.replace("?", ""));
        if (parsedSearch.returnUrl) {
          history.replace({ pathname: parsedSearch.returnUrl });
        } else {
          history.replace({ pathname: homePath });
        }
      } else if (
        history.location.pathname === signInPath ||
        history.location.pathname === signUpPath
      ) {
        history.replace({ pathname: homePath });
      }
    }

    shouldRedirectToLogin() {
      const {
        location: { pathname }
      } = this.props;
      return (
        !this.props.loggedIn &&
        pathname !== signUpPath &&
        pathname !== forgotPassPath &&
        pathname !== resetPassPath
      );
    }

    render() {
      return this.shouldRedirectToLogin() ? (
        <Login></Login>
      ) : (
        <Component {...this.props}></Component>
      );
    }
  }
  return withRouter(
    connect(({ user: { loggedIn } }) => {
      return {
        loggedIn
      };
    })(AuthComponent)
  );
};

答案 4 :(得分:0)

谢谢,经过大量研究,我只能得到:

const  params  = (this.props.children.props.computedMatch.url);
       return <Redirect to={`/login/?next=${params}`} />;