我在本地存储中有一个JWT令牌,也有一个User mobx存储。
应用启动时,我向后端有一个获取令牌解码请求。所以我想等待这个请求的结束,然后选择react-router开关。就像角度2+中的异步防护一样。
这是我的代码:
class App extends React.Component<AppProps> {
public render() {
return (
<div className="App">
<Observer>
{() =>
this.props.spinnerStore.spinner ? (
<div className="spin-container">
<Spin spinning={this.props.spinnerStore.spinner} size="large" />
</div>
) : null
}
</Observer>
<Observer>
{() =>
this.props.userStore.get().id ? (
<Switch>
<Route exact path="/" render={() => <Home userStore={userStore} />} />
<Redirect from="*" to="/" />
</Switch>
) : (
<Switch>
<Route exact path="/" render={() => <Home userStore={userStore} />} />
<Route path="/signin" render={() => <SignIn userStore={userStore} />} />
<Route path="/signup" render={() => <SignUp spinnerStore={spinnerStore} />} />
<Route path="/change-password" render={() => <ForgotPassword spinnerStore={spinnerStore} />} />
<Route
path="/activate/:token"
render={({ match }) => <ActivateAccount match={match} userStore={userStore} />}
/>
<Route
path="/callback/:token"
render={({ match }) => <ApiCallback match={match} userStore={userStore} />}
/>
<Route
path="/reset/:token"
render={({ match }) => <ResetPassword match={match} userStore={userStore} />}
/>
<Redirect from="*" to="/" />
</Switch>
)
}
</Observer>
</div>
);
}
}
export class UserStore implements IUserStore {
constructor() {
const token = this.tokenService.get();
if (!token) {
return;
}
this.userService
.get()
.then((user: UserModel) => {
this.user = user;
})
.catch(() => {
this.tokenService.reset();
});
}
有什么想法吗?