onEnter未在React-Router中调用

Tra*_*ace 57 javascript reactjs react-router react-router-v4

好吧,我厌倦了尝试.
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")
Run Code Online (Sandbox Code Playgroud)

编辑:

我打电话时执行该方法onEnter={requireAuth()},但显然这不是目的,我也不会得到所需的参数.

Dei*_*kas 103

onEnter不再存在react-router-4.您应该使用<Route render={ ... } />获得所需的功能.我相信Redirect例子有你的具体情况.我在下面修改它以匹配你的.

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

  • 如果isLoggedIn是Async函数会发生什么? (9认同)
  • @Smily 那会如何运作?渲染回调实际上没有返回任何内容。 (3认同)
  • @EgoSlayer如果出现[** Promisified **](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise)isLoggedIn`render = {()=&gt; { isLoggedIn()。then(res =&gt; {return res?(&lt;重定向到=“ / front” /&gt;):(&lt;Home /&gt;}}}}}` (2认同)

fan*_*ing 27

根据有关从v2/v3迁移到v4的文档,来自react-router-v4 onEnter,onUpdate并将onLeave其删除:

on*性能
阵营路由器v3提供onEnter,onUpdateonLeave 方法.这些本质上是重建React的生命周期方法.

使用v4,您应该使用由a呈现的组件的生命周期方法<Route>.而不是onEnter,你会使用 componentDidMountcomponentWillMount.当你会用onUpdate,你可以使用componentDidUpdatecomponentWillUpdate(或可能 componentWillReceiveProps).onLeave可以替换为 componentWillUnmount.

  • ComponentWillMount 已弃用:https://reactjs.org/docs/react-component.html ComponentDidMount 是更好的选择。 (4认同)