我似乎无法理解处理来宾和授权路线的正确方法。我查看了给定的示例https://reacttraining.com/react-router/web/example/auth-workflow,但dosnt阻止授权用户打开/登录路由,似乎所有给定的示例都是这样做的。
我尝试过这样的事情:
export default function requireGuest(WrappedComponent) {
class Guest extends Component {
render() {
if (this.props.authenticated) {
return <Redirect to="/agenda"/>
}
return <WrappedComponent {...this.props}/>
}
}
function mapStateToProps(state) {
return {authenticated: isLoggedInSelector(state)}
}
const withConnect = connect(mapStateToProps, null, null, {pure: false});
return compose(
withConnect,
withRouter
)(Guest);
}
class Authorized extends Component {
render() {
if (!this.props.authenticated) {
return <Redirect to="/login"/>
}
return <WrappedComponent {...this.props}/>
}
}
function mapStateToProps(state) {
return {authenticated: isLoggedInSelector(state)}
}
const withConnect = connect(mapStateToProps, null, null, {pure: false});
return compose(
withConnect,
withRouter
)(Authorized);
}
然后在主容器中执行以下操作:
<Route path='/login' component={RequireGuest(LoginPage)}/>
<Route path='/register' component={RequireGuest(RegisterPage)}/>
<Route path="/dashboard" component={RequireAuthorization(DashboardPage)}/>
但是当我尝试在其他任何地方导航时,路径更新和状态也会更新,但没有重新渲染,也没有重定向。
然后我尝试了这样的事情:
class GuestRoutes extends Component {
render() {
const {loggedIn} = this.props;
return (
<Route
render={props =>
loggedIn ? (
<Redirect
to={{
pathname: "/agenda",
state: {from: props.location}
}}
/>
) : (
<Switch>
<Route path='/login' component={LoginPage}/>
<Route path='/register' component={RegisterPage}/>
<Redirect to='/login'/>
</Switch>
)
}
/>
);
}
}
class AuthorizedRoutes extends Component {
render() {
const {loggedIn} = this.props;
return (
<Route
render={props =>
loggedIn ? (
<Switch>
<Route exact path="/dashboard" component={DashboardPage}/>
<Redirect to="/dashboard"/>
</Switch>
) :
(<Redirect
to={{
pathname: "/login",
state: {from: props.location}
}}
/>)
}
/>
);
}
}
在主容器中
<Switch>
<GuestRoutes/>
<AuthorizedRoutes/>
</Switch>
但是如果用户登录,则访客路由将一直呈现,直到获得深度错误。
我一直试图弄清楚这几个小时,所以我在这里绝望。所以任何示例或任何根据授权状态保护路由的内容