好吧,我受够了。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
根据从V2/V3到V4迁移的文档:
on*
属性
React路由器V3提供onEnter
,onUpdate
和onLeave
方法。这些本质上是重现React的生命周期方法。使用V4,您应该使用组件的生命周期方法 由
<Route>
渲染。而不是onEnter
,您将使用componentDidMount
或componentWillMount
。在哪里使用onUpdate
, 您可以使用componentDidUpdate
或componentWillUpdate
(或可能componentWillReceiveProps
)。onLeave
可以替换componentWillUnmount
。
react-router-6
Redirect
组件已被Navigate
替换。
userState
下面的
将根据用户登录是否为null或填充,例如您的REDUX状态。
<Route path="/protectedRoute"
element={userState ? <protectedComponent/> : <Navigate to="/login"/>}/>