on enter未在反复路由器中调用



好吧,我受够了。
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()}时执行该方法,但显然这不是目的,而且我也不会获得所需的参数。

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

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

来自React-Router-V4 onEnteronUpdateonLeave根据从V2/V3到V4迁移的文档:

on*属性
React路由器V3提供onEnteronUpdateonLeave 方法。这些本质上是重现React的生命周期方法。

使用V4,您应该使用组件的生命周期方法 由<Route>渲染。而不是onEnter,您将使用 componentDidMountcomponentWillMount。在哪里使用onUpdate, 您可以使用componentDidUpdatecomponentWillUpdate(或可能 componentWillReceiveProps)。onLeave可以替换 componentWillUnmount

react-router-6 Redirect组件已被Navigate替换。

userState下面的

将根据用户登录是否为null或填充,例如您的REDUX状态。

<Route path="/protectedRoute"
            element={userState ? <protectedComponent/> : <Navigate to="/login"/>}/>

最新更新