本文介绍了onEnter未在React-Router中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,我厌倦了尝试。
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.
推荐答案
onEnter
>。您应该使用< Route render = {...} />
来获得所需的功能。我相信示例有你的具体情况。我在下面修改它以匹配你的。
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 />
)
)}/>
这篇关于onEnter未在React-Router中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!