没有在 React-Router 中调用 onEnter
onEnter not called in 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()}
时执行,但显然这不是目的,我也得不到想要的参数。
onEnter
在 react-router-4
上不再存在。您应该使用 <Route render={ ... } />
来获得您想要的功能。我相信 Redirect
示例有您的具体情况。我在下面对其进行了修改以匹配您的。
<Route exact path="/home" render={() => (
isLoggedIn() ? (
<Redirect to="/front"/>
) : (
<Home />
)
)}/>
从 react-router-v4 onEnter
、onUpdate
和 onLeave
中删除,
根据 migrating from v2/v3 to v4 上的文档:
on*
properties
React Router v3 provides onEnter
, onUpdate
, and onLeave
methods. These were essentially recreating React's lifecycle methods.
With v4, you should use the lifecycle methods of the component
rendered by a <Route>
. Instead of onEnter
, you would use
componentDidMount
or componentWillMount
. Where you would use onUpdate
,
you can use componentDidUpdate
or componentWillUpdate
(or possibly
componentWillReceiveProps
). onLeave
can be replaced with
componentWillUnmount
.
好吧,我受够了。
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
在 react-router-4
上不再存在。您应该使用 <Route render={ ... } />
来获得您想要的功能。我相信 Redirect
示例有您的具体情况。我在下面对其进行了修改以匹配您的。
<Route exact path="/home" render={() => (
isLoggedIn() ? (
<Redirect to="/front"/>
) : (
<Home />
)
)}/>
从 react-router-v4 onEnter
、onUpdate
和 onLeave
中删除,
根据 migrating from v2/v3 to v4 上的文档:
on*
properties
React Router v3 providesonEnter
,onUpdate
, andonLeave
methods. These were essentially recreating React's lifecycle methods.With v4, you should use the lifecycle methods of the component rendered by a
<Route>
. Instead ofonEnter
, you would usecomponentDidMount
orcomponentWillMount
. Where you would useonUpdate
, you can usecomponentDidUpdate
orcomponentWillUpdate
(or possiblycomponentWillReceiveProps
).onLeave
can be replaced withcomponentWillUnmount
.