我已经稍微调整了专用路由的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