小编典典

在React-Router中未调用onEnter

reactjs

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


阅读 557

收藏
2020-07-22

共1个答案

小编典典

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

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