编程语言
首页 > 编程语言> > javascript – onEnter未在React-Router中调用

javascript – onEnter未在React-Router中调用

作者:互联网

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

解决方法:

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

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

标签:react-router-v4,javascript,reactjs,react-router
来源: https://codeday.me/bug/20190925/1817528.html