React Router-如何将用户路由到他们刚来自的页面?

时间:2019-02-23 03:20:30

标签: reactjs

很抱歉,这是React Router文档中的第一件事,我很难拼凑东西。

**我有一些受保护的路由,没有登录就单击它们,将其路由到登录页面,但是在成功按下登录按钮后,我希望它们返回到它们刚来自的受保护路由**

例如点击/ user_only => loginForm =>成功登录=>路由到/ user_only

这是成功登录后(转到/ home)的路由代码。

Array
(
    [title] => New Content
    [message] => A new content "Gully Boy" has been added to Movie category.
    [notification_type] => 1
    [user_id] => 323507
)

Array
(
    [title] => New Content
    [message] => A new content "Gully Boy" has been added to Movie category.
    [notification_type] => 1
    [user_id] => 323522
)

但是,我想推送到用户刚来自的任何地方,而不是this.props.history.push(“ / home”)。

我记得一个名为“ from”的react路由器属性可能解决了我的问题(我不知道它的作用,但直观上看,它似乎是用户来自的网址),但是我找不到我曾经来过的地方穿过它。

2 个答案:

答案 0 :(得分:1)

一种可靠的方法是为所有受保护的路由创建一个PrivateRoute高阶组件,捕获用户最初登陆的私有路径路由,并在未通过身份验证的情况下处理重定向到登录页面的操作。 / p>

然后可以将该路径存储为url参数,登录路由将使用该参数来重定向用户发布身份验证。

PrivateRoute.js

import React from 'react';
import { Route, Redirect, withRouter } from 'react-router';

const PrivateRoute = ({ component: Component, ...rest }) => {
  let redirectUrl = '';
  if (rest.location.pathname !== '/') {
    const redirectPathName = rest.location.pathname;
    const redirectParams = rest.location.search;
    redirectUrl = `redirectUrl=${encodeURIComponent(`${redirectPathName}${redirectParams}`)}`;
  }
  return (
    <Route
      {...rest}
      render={props => sessionStorage.token ? <Component {...props} /> : <Redirect to={{ pathname: '/login', search: redirectUrl }} />}
    />
  );
};

export default withRouter(PrivateRoute);

Login.js

import queryString from 'query-string';
import { withRouter } from 'react-router';

const Login = ({ history }) => {
  const onLogin = () => {
    const isAuthenticatd = false;

    // Perform authentication here and if authentication is successfull

    const queryParams = queryString.parse(history.location.search)
    if (isAuthenticatd && queryParams.redirectUrl) {
      history.push(queryParams.redirectUrl);
    } else {
      history.push('path to default landing page post authentication');
    }
  };
  return (
    <button onClick={onLogin} />
  );
};

export default withRouter(Login);

App.jsx

import { Route } from 'react-router';
import PrivateRoute from '/path/to/privateroute/component';
import YourPrivateComponent from '/path/to/component';
import Login from '/path/to/Login';

const App = () => {
  return (
    <Switch>
      <PrivateRoute path="yourPrivatePath" component={YourPrivateComponent} />
      <Route path="login" component={Login} />
    </Switch>
  );
}

export default App;

请注意:PrivateRouteLogin必须用withRouter的{​​{1}} Hoc包裹,才能访问react-router

答案 1 :(得分:-1)

嗯,我刚刚看到一个人发布了答案,但是出于某种原因将其删除。无论如何,他用 this.props.history.goBack()回答了,我认为现在唯一的潜在错误是,如果用户直接转到“ / loginForm”,则无法返回( ),无处可退。我确定必须有一些包含先前URL的字段,然后执行if prev == null then this.props.history.push("home")。当我找到能做到这一点的历史支柱时,将更新此答案。