Javascript 在 React-Router 中未调用 onEnter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42768620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:25:30  来源:igfitidea点击:

onEnter not called in React-Router

javascriptreactjsreact-routerreact-router-v4

提问by Trace

Ok, I'm fed up trying.
The onEntermethod doesn't work. Any idea why is that?

好吧,我厌倦了尝试。
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")

Edit:

编辑:

The method is executed when I call onEnter={requireAuth()}, but obviously that is not the purpose, and I also won't get the desired parameters.

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

回答by Deividas Karzinauskas

onEnterno longer exists on react-router-4. You should use <Route render={ ... } />to get your desired functionality. I believe Redirectexample has your specific scenario. I modified it below to match yours.

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

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

回答by fangxing

From react-router-v4 onEnter, onUpdate, and onLeaveis removed, according the documentation on migrating from v2/v3 to v4:

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

on*properties
React Router v3 provides onEnter, onUpdate, and onLeavemethods. These were essentially recreating React's lifecycle methods.

With v4, you should use the lifecycle methods of the component rendered by a <Route>. Instead of onEnter, you would use componentDidMountor componentWillMount. Where you would use onUpdate, you can use componentDidUpdateor componentWillUpdate(or possibly componentWillReceiveProps). onLeavecan be replaced with componentWillUnmount.

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

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