尝试设置专用路由组件,该组件会在用户的authToken
无效时进行更新。
这是私人路线:
const PrivateRoute = observer(({component: Component, ...rest}: { component: any, path: any }) => {
return (<Route {...rest} render={(props: any) => (
authCredentialsStore.credToken
? <Component {...props} />
: <Redirect to='/login'/>
)}/>);
});
authCredentialsStore
是通过导入提供的。
这是商店:
class AuthCredentialsStore {
@observable _authCredentials: AuthCredentials;
@observable credToken = this._authCredentials ? this._authCredentials.authToken : null;
set authCredentials(creds: AuthCredentials) {
this._authCredentials = creds;;
}
get authCredentials() {
return this._authCredentials;
}
removeCredentials() {
this._authCredentials = null;
}
}
export const authCredentialsStore = new AuthCredentials();
然后在子组件中,对componentDidMount
进行抓取,如果抓取失败,我想重置存储并将用户重定向到登录页面:
class ChildComponent extends React.Component<any, any> {
fetchItems(): void {
const authToken = authCredentialsStore.credToken;
const options = {
method: 'GET',
headers: {
'Authorization': `${authToken}`
}
};
fetch('some_url', options)
.then(res => {
if (!res.ok) {
authCredentialsStore.removeCredentials();
}
return res.json();
})
.then(/*do something with results*/))
.catch(/*do error handling*/);
}
componentDidMount() {
this.fetchItems();
}
render() {...}
}
我希望可以重置authToken并在专用路由上自动触发setState
,这将导致它重新呈现,并重定向到登录页面,但这不会在第一次执行时发生。似乎在商店中清除了authToken
时,在PrivateRoute组件中未检测到更改。