如何使用React Router的重定向功能?

JD.*_*JD. 22 routing reactjs react-router

我想以下列方式配置React Router.如果匹配某个路由,则将用户重定向到另一个路由.文档说明它是可能的,但没有提供实现这一目标的确切方法.有没有人对此有所了解?

type EnterHook = (nextState: RouterState, replaceState: RedirectFunction, callback?: Function) => any;

type RedirectFunction = (state: ?LocationState, pathname: Pathname | Path, query: ?Query) => void;
Run Code Online (Sandbox Code Playgroud)

Jor*_*ing 37

编辑 请参阅新的,不推荐的react-router语法的其他答案


onEnterauth-flow示例中有一个很好的示例如何使用钩子.这是相关的代码:

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

render((
  <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>
), document.getElementById('example'))
Run Code Online (Sandbox Code Playgroud)

如您所见,当/dashboard访问路径时,将调用该requireAuth函数.它接收两个参数:nextState,这是一个RouterState代表用户即将进入状态对象,并且replaceState,一个RedirectFunction可以被称为别的东西来替换状态.在这种情况下,如果用户未登录,则requireAuth调用replaceState如下:

replaceState({ nextPathname: nextState.location.pathname }, '/login')
Run Code Online (Sandbox Code Playgroud)

第二个参数显然是用户将被重定向到的路径名.第一个参数是一个对象,它可以包含我们希望路由处理程序(在本例中为Login组件)具有的任何数据.这里,用户尝试转到的路径名(/dashboard)被设置为nextPathname属性,因此在登录后,用户可以重定向到该页面(请参阅组件中的handleSubmit方法Login).

如果用户已登录,requireAuth则不执行任何操作,并且由于replaceState从未调用过,因此路径可以正常工作,也就是说Dashboard组件已呈现.


Dan*_*nny 16

从react-router 2.0.0起,任何人都会阅读这个问题,现在不推荐使用replaceState(state,pathname,query).您现在必须使用替换(位置)替换位置描述符.

https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#link-to-onenter-and-isactive-use-location-descriptors

从他们的指南:

// v1.0.x
(nextState, replaceState) => replaceState(null, '/foo')
(nextState, replaceState) => replaceState(null, '/foo', { the: 'query' })

// v2.0.0
(nextState, replace) => replace('/foo')
(nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } })
Run Code Online (Sandbox Code Playgroud)


小智 10

以下是如何使用react-router2.0.0(使用replace而不是replaceState)执行此操作的示例:

router.jsx中:

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组件中,您可以在成功登录后重定向,如下所示:

import { browserHistory } from 'react-router';

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)