在 React-Router 中未调用 onEnter [英] onEnter not called in React-Router

查看:29
本文介绍了在 React-Router 中未调用 onEnter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我厌倦了尝试.
onEnter 方法不起作用.知道这是为什么吗?

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

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

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.

推荐答案

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

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

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

这篇关于在 React-Router 中未调用 onEnter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆