我正在使用React Router v5.2.0并通过异步身份验证实现公共/私有路由。 本质上,工作流程是: 用于登录的PublicRoute, 仪表板的PrivateRoute 和/ landing的PublicRoute(因此,如果用户已登录,但他们未订阅服务,则将其重定向到登录页面)。
除“ /着陆”外,我所有的路线均有效 该应用程序将成功重定向到/ landing,但Landing组件未显示/安装。 (console.log也不会触发)
我正在使用redux,并且尝试添加withRouter,但收到相同的错误。 如果我删除了公共或私人路线组件并使用常规路线,则会显示该组件。
App.js
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/" component={Dashboard} />
<PublicRoute exact restricted={true} path="/landing" component={Landing} />
<PublicRoute exact restricted={false} path="/login" component={Login} />
</Switch>
</BrowserRouter>
公共路线:
class PublicRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
isAuthenticated: false,
isSubscribed: false
};
}
async componentDidMount() {
console.log("loading");
const isLoginCheck = await isLogin();
const isSubscribedCheck = await isSubscribed();
this.setState({
loading: false,
isAuthenticated: isLoginCheck || false,
isSubscribed: isSubscribedCheck || false
})
}
render() {
const { component: Component, restricted, ...rest } = this.props;
return (
<Route
{...rest}
render={props => (
//If a user is authenticated, subscribed and the route is restricted, redirect to dashboard
this.state.isAuthenticated && this.state.isSubscribed && restricted ? (
<Redirect to="/" />
) : this.state.loading ? (
//If loading, show a loading component (placeholder currently)
<div>LOADING</div>
) : this.state.isAuthenticated && (!this.state.isSubscribed) ? (
//If the user is authenticated, but not subscribed. redirect to landing
<Redirect to="/landing" />
) :
(
//Else redirect to the component.
<Component {...props} />
))
}
/>
);
}
}
export default PublicRoute;
着陆:
class Landing extends React.Component {
componentDidMount() {
console.log('component mounted');
}
render() {
console.log('Component was called');
return (
<h1>Landing page - not a valid subscriber. </h1>
)
}
}
export default Landing;
谢谢!