在 React-Router 中未调用 onEnter

IT技术 javascript reactjs react-router react-router-v4
2021-04-19 05:06:28

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

2个回答

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

<Route exact path="/home" render={() => (
  isLoggedIn() ? (
    <Redirect to="/front"/>
  ) : (
    <Home />
  )
)}/>
虽然,我今天注意到这实际上并没有呈现重定向到的新 url 的组件。这是理想的行为吗?好像不太合逻辑……
2021-05-23 05:06:28
如果 isLoggedIn 是 Async 函数会发生什么?
2021-05-26 05:06:28
@KimGysen 不,这不是默认行为。如果您正在使用Switch组件,则Redirect应按预期呈现。但是,如果您不使用Switch,Redirect将不会被呈现(因为我假设是您的用例)。
2021-05-28 05:06:28
@EgoSlayer 在Promisified isLoggedIn 的情况下render={ () => { isLoggedIn().then( res => { return res ? ( <Redirect to="/front"/> ) : ( <Home /> )}) }}
2021-05-30 05:06:28
@Smily 这将如何工作?渲染回调实际上并没有返回任何东西。
2021-06-13 05:06:28

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

on*性能
阵营路由器v3提供onEnteronUpdateonLeave 方法。这些本质上是重新创建 React 的生命周期方法。

在 v4 中,您应该使用由<Route>. 取而代之的是onEnter,您将使用 componentDidMountcomponentWillMount在您将使用的地方onUpdate,您可以使用componentDidUpdatecomponentWillUpdate(或可能 componentWillReceiveProps)。onLeave可以替换为 componentWillUnmount

不推荐使用 ComponentWillMount:reactjs.org/docs/react-component.html ComponentDidMount 是更好的选择。
2021-06-09 05:06:28