好吧,我受够了尝试。 该onEnter方法不起作用。知道为什么吗?
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()},但是显然这不是目的,而且我也不会获得所需的参数。
onEnter={requireAuth()}
onEnter不再存在react-router-4。您应该使用它<Route render={ ... } />来获得所需的功能。我相信Redirect示例具有您的特定情况。我在下面对其进行了修改,使其与您的匹配。
react-router-4
<Route render={ ... } />
Redirect
<Route exact path="/home" render={() => ( isLoggedIn() ? ( <Redirect to="/front"/> ) : ( <Home /> ) )}/>