Javascript 在React路由器中未调用onEnter

Javascript 在React路由器中未调用onEnter,javascript,reactjs,react-router,react-router-v4,Javascript,Reactjs,React Router,React Router V4,好吧,我受够了尝试。 onEnter方法不起作用。知道为什么吗 // Authentication "before" filter function requireAuth(nextState, replace){ console.log("called"); // => Is not triggered at all if (!isLoggedIn()) { replace({ pathname: '/front' }) } } // Rend

好吧,我受够了尝试。
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")
//验证“之前”过滤器
功能要求授权(下一状态,替换){
console.log(“调用”);//=>根本不会被触发
如果(!isLoggedIn()){
替换({
路径名:'/front'
})
}
}
//渲染应用程序
渲染(
,
document.getElementById(“lf应用程序”)
编辑:


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

onEnter
react-router-4
上不再存在。您应该使用
来获得所需的功能。我相信示例有您的特定场景。我在下面对其进行了修改,以匹配您的场景

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

从react-router-v4
OnNet
onUpdate
onLeave
被删除, 根据以下文件:

打开*
属性

React路由器v3提供了
onEnter
onUpdate
onLeave
这些基本上是重新创建React的生命周期方法

对于v4,您应该使用组件的生命周期方法 由
渲染。您可以使用
componentDidMount
componentWillMount
。您将使用
onUpdate
, 您可以使用
componentdiddupdate
componentWillUpdate
(或者可能
组件将接收道具
)。
onLeave
可以替换为
组件将卸载


您使用的是哪个react路由器版本?虽然,我今天注意到,这实际上并没有呈现重定向到的新url的组件。这是期望的行为吗?似乎不太符合逻辑…@KimGysen不,这不是默认行为。如果您使用的是
开关
组件,则应呈现
重定向
但是,如果您没有使用
开关
重定向
将不会被呈现(我假设这是您的用例)。如果isLoggedIn是异步函数,会发生什么情况?@EgoSlayer在isLoggedIn
呈现={()=>{isLoggedIn()。然后(res=>{return res?():()}}
@Smily这是怎么回事?渲染回调实际上并没有返回任何内容。ComponentWillMount已被弃用:ComponentDidMount是更好的选择。