react router - 登录后重定向

Mah*_*ind 22 react-router

能否帮助我理解我可以使用最新版本的反应路由器(v1.1.0)的重定向机制.我想重定向到一个url取决于用户登录的成功或失败.我试图做以下事情首先使用创建历史记录.

let history = createBrowserHistory();
Run Code Online (Sandbox Code Playgroud)

然后尝试用推动状态

history.pushState(null, 'abc')
Run Code Online (Sandbox Code Playgroud)

什么都没发生.你能不能让我知道正确的转换方式.从我理解的文档transitionTo()中,最新版本中没有API.如果你能指出一个简单的工作实例,它会很棒.

提前致谢.

小智 26

想要更新这个帖子,因为我花了很多时间在这上面挖掘.在React Router 2.0.x中,replaceState不赞成使用replace.详情请见:https://github.com/ReactTraining/react-router/blob/v2.0.0/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

正确的方法是这样的:

function requireAuth(nextState, replace) {
  if (!userExists()) {
    replace({
      pathname: '/signin',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

export const renderRoutes = () => (
  <Router history={browserHistory}>
      <Route path="protectedRoute" component={Protected} onEnter={requireAuth} />
      <Route path="signin" component={SignIn} />
    </Route>
  </Router>
);
Run Code Online (Sandbox Code Playgroud)

然后,在SignIn组件中,您可以在成功登录后重定向,如下所示:

signInFunction({params}, (err, res) => {
  // Now in the sign in callback
  if (err)
    alert("Please try again")
  else {
    const location = this.props.location
    if (location.state && location.state.nextPathname) {
      browserHistory.push(location.state.nextPathname)
    } else {
      browserHistory.push('/')
    }
  }
})
Run Code Online (Sandbox Code Playgroud)


ter*_*sin 18

您可以在进入和离开路线时触发的路线上注册"挂钩".查看onEnter和onLeave挂钩的文档.

还有一个示例要求路由上的auth,如果用户未登录,则重定向到不同的路径.

这是从app.js中的require auth示例中获取的代码段:

function requireAuth(nextState, replaceState) {
  if (!auth.loggedIn())
    replaceState({ nextPathname: nextState.location.pathname }, '/login')
}

// And from the route configuration, use the requireAuth function in onEnter...
<Router history={history}>
  <Route path="/" component={App}>
    <Route path="login" component={Login} />
    <Route path="logout" component={Logout} />
    <Route path="about" component={About} />
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
  </Route>
</Router>
Run Code Online (Sandbox Code Playgroud)

nextStatereplaceState参数是从对象rackt /历史并获得注入你进入的OnEnter方法.


Joh*_*nSz 9

@terranmoccasin的回答是正确的.然而,通常需要很少的例子来解决.

假设您需要保护多条路线(仪表板1,仪表板2,......).成功登录后,如何重定向回原始页面?换句话说,你做什么用的{nextPathname: nextState.location.pathname}

这是我做的./containers/LoginContainer.js:

import { push } from 'react-router-redux';
const mapStateToProps = (state) => ({
  nextPathname: state.routing.locationBeforeTransitions.state.nextPathname,
});
const mapDispatchToProps = (dispatch) => ({
  changeLocationOnSignIn: (nextPathname) => {
    dispatch(push(nextPathname));
  },
});
Run Code Online (Sandbox Code Playgroud)

并在 ./components/Login.js

componentWillReceiveProps(nextProps) {
  // user signed in or signed up, assuming redux. you may use this elsewhere.
  if (nextProps.user.status === 'authenticated' && nextProps.user.user &&
     !nextProps.user.error) {
       this.props.changeLocationOnSignIn(this.props.nextPathname);
  }
Run Code Online (Sandbox Code Playgroud)

React-router 2.4.0(2016年4月)引入了与创建HOC的路由器.但是它包装了React.createClass,而不是JS类.我还没有能够使用redux-form等工作.此外我认为上面的代码更容易理解.


MD *_*hik 8

反应路由器v4.2

我正在使用React-16.2React-router-4.2

然后我得到解决方案 this.props.history.push("/");

我的工作代码:

    .then(response => response.json())
        .then(data => {
            if(data.status == 200){
                this.props.history.push("/");
                console.log('Successfully Login');
          }
        })
Run Code Online (Sandbox Code Playgroud)

我正在关注此文档的登录和注销重定向

  • 像魅力一样工作 (2认同)

小智 7

我只想分享 2020 年的实际答案。在状态中存储先前位置的主要方式是相同的。但是 onEnter 已从库中删除。现在我们可以像文档中一样使用 AuthRoute :

<AuthRoute exact path="/food">
  <Food />
</AuthRoute>
<Route exact path="/login">
  <Login />
</Route>
Run Code Online (Sandbox Code Playgroud)
const AuthRoute = ({ children, isAuthorized, ...rest }) => {
  const loginLink = usePrepareLink({
    to: "/login",
    isRelativePath: true
  });

  return (
    <Route {...rest} render={({ location }) =>
      isAuthorized ? (
        children
      ) : (
        <Redirect to={{
          ...loginLink,
          state: { from: location }
        }} />
      )
    } />
  );
};
Run Code Online (Sandbox Code Playgroud)

我们可以在登录后使用状态恢复以前的 URL

const onSignIn = useCallback(() => {
  setIsAuthorized(value);
  const link = (state && state.from) || "/restore-prevented-route";
  history.replace(link);
}, [setIsAuthorized, value, history, state]);
Run Code Online (Sandbox Code Playgroud)

您可以在此处(或RU)找到详细信息