在React-Router中未调用onEnter

JavaScript React.js

小宇宙GilMandy

2020-03-19

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

第2319篇《在React-Router中未调用onEnter》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
飞羽Jim 2020.03.19

从反应路由器-V4 onEnteronUpdateonLeave被删除,根据所述文档从V2 / V3到V4迁移

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

对于v4,您应该使用由呈现的组件的生命周期方法<Route>取而代之的是onEnter,您可以使用 componentDidMountcomponentWillMount您可以使用的地方onUpdate,可以使用componentDidUpdatecomponentWillUpdate(或可能 componentWillReceiveProps)。onLeave可以替换为 componentWillUnmount

前端逆天前端 2020.03.19

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android