我已經稍微調整了專用路由的React路由器示例,以便與Redux一起玩,但在鏈接或重定向到其他「頁面」時不顯示任何組件。這個例子可以在這裏找到:React路由器私有路由/重定向不起作用
https://reacttraining.com/react-router/web/example/auth-workflow
他們PrivateRoute組件看起來是這樣的:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
但是,因爲我已經在一個終極版的應用程序結合的話,我不得不調整PrivateRoute一點這樣我就可以訪問了Redux店,以及路線道具:
const PrivateRouteComponent = (props) => (
<Route {...props.routeProps} render={() => (
props.logged_in ? (
<div>{props.children}</div>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />)
)} />
);
const mapStateToProps = (state, ownProps) => {
return {
logged_in: state.auth.logged_in,
location: ownProps.path,
routeProps: {
exact: ownProps.exact,
path: ownProps.path
}
};
};
const PrivateRoute = connect(mapStateToProps, null)(PrivateRouteComponent);
export default PrivateRoute
每當我不登錄,並觸及PrivateRoute,我是心病直接重定向到/登錄。但是,例如,在登錄並使用<Redirect .../>
或點擊任何<Link ...>
到PrivateRoute後,URI會更新,但視圖不會。它保持在同一個組件上。
我在做什麼錯?
剛剛完成的圖片,在應用程序的index.js
有一些無關痛癢的東西,這些路由設置是這樣的:
ReactDOM.render(
<Provider store={store}>
<App>
<Router>
<div>
<PrivateRoute exact path="/"><Home /></PrivateRoute>
// ... other private routes
<Route path="/login" component={Login} />
</div>
</Router>
</App>
</Provider>,
document.getElementById('root')
);
謝謝,我會在晚些時候看看! :-D – Rein
我有類似的問題。事實上,我不想通過isAuthenticated到每一次使用PrivateRoute,這是我連接到Redux的原因,但令人驚訝的是,直到任何額外的道具傳遞給
@Danijel,你搖滾! :-) – kernix