【问题标题】:onEnter not called in React-Router在 React-Router 中未调用 onEnter
【发布时间】:2017-08-03 18:19:30
【问题描述】:

好吧,我受够了尝试。
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()}时该方法被执行,但显然这不是目的,我也不会得到想要的参数。

【问题讨论】:

  • 你使用的是哪个 react-router 版本?

标签: javascript reactjs react-router react-router-v4


【解决方案1】:

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

<Route exact path="/home" render={() => (
  isLoggedIn() ? (
    <Redirect to="/front"/>
  ) : (
    <Home />
  )
)}/>

【讨论】:

  • 虽然,我今天注意到这实际上并没有呈现重定向到的新 url 的组件。这是期望的行为吗?看起来不太合乎逻辑……
  • @KimGysen 不,这不是默认行为。如果您使用的是Switch 组件,那么Redirect 应该按预期呈现。但是,如果您不使用Switch,则不会呈现Redirect(我假设是您的用例)。
  • 如果 isLoggedIn 是异步函数会发生什么?
  • @EgoSlayer 如果是Promisified isLoggedIn render={ () =&gt; { isLoggedIn().then( res =&gt; { return res ? ( &lt;Redirect to="/front"/&gt; ) : ( &lt;Home /&gt; )}) }}
  • @Smily 这将如何工作?渲染回调实际上并没有返回任何东西。
【解决方案2】:

从 react-router-v4 中删除 onEnteronUpdateonLeave, 根据migrating from v2/v3 to v4上的文档:

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

在 v4 中,您应该使用组件的生命周期方法 由&lt;Route&gt; 渲染。而不是onEnter,你会使用 componentDidMountcomponentWillMount。你会在哪里使用onUpdate, 你可以使用componentDidUpdatecomponentWillUpdate(或者可能 componentWillReceiveProps)。 onLeave 可以替换为 componentWillUnmount.

【讨论】:

猜你喜欢
  • 2017-04-30
  • 2017-03-01
  • 2017-09-04
  • 2018-01-07
  • 2016-07-22
  • 1970-01-01
  • 2016-07-21
  • 2016-09-09
  • 2016-06-27
相关资源
最近更新 更多