71

好吧,我受够了尝试。
onEnter方法不起作用。知道为什么吗?

// Authentication "before" filter
function requireAuth(nextState, replace){
  console.log("called"); // => Is not triggered at all 
  if (!isLoggedIn()) {
    replace({
      pathname: '/front'
    })
  }
}

// Render the app
render(
  <Provider store={store}>
      <Router history={history}>
        <App>
          <Switch>
            <Route path="/front" component={Front} />
            <Route path="/home" component={Home} onEnter={requireAuth} />
            <Route exact path="/" component={Home} onEnter={requireAuth} />
            <Route path="*" component={NoMatch} />
          </Switch>
        </App>
      </Router>
  </Provider>,
  document.getElementById("lf-app")

编辑:

该方法在我调用时执行onEnter={requireAuth()},但显然这不是目的,我也不会得到所需的参数。

4

2 回答 2

135

onEnter上不再存在react-router-4。您应该使用<Route render={ ... } />来获得所需的功能。我相信Redirect例子有你的具体情况。我在下面修改了它以匹配你的。

<Route exact path="/home" render={() => (
  isLoggedIn() ? (
    <Redirect to="/front"/>
  ) : (
    <Home />
  )
)}/>
于 2017-03-13T16:55:32.443 回答
32

根据从 v2/v3 迁移到 v4的文档,从 react-router-v4 onEnteronUpdateonLeave中删除:

on*属性
React Router v3 提供onEnteronUpdateonLeave 方法。这些本质上是重新创建 React 的生命周期方法。

在 v4 中,您应该使用由 a 呈现的组件的生命周期方法<Route>。代替onEnter,您将使用 componentDidMountor componentWillMount。在您将使用的地方onUpdate,您可以使用componentDidUpdatecomponentWillUpdate(或可能 componentWillReceiveProps)。onLeave可以替换为 componentWillUnmount

于 2018-02-06T06:56:09.740 回答