在Web应用程序中,我在另一个React应用程序中重复使用dataProvider
网站上指定的react-admin
:https://marmelab.com/react-admin/DataProviders.html#data-providers。
如果有任何请求返回401
响应,他们可以断开连接并重定向到登录。
在我的另一个不是React admin的其他React应用中,当我的请求失败(会话超时)时,我没有此重定向。
这是我的dataProvider
的外观:
const dataProvider = {
getList: (resource, params) => Promise,
getOne: (resource, params) => Promise,
getMany: (resource, params) => Promise,
getManyReference: (resource, params) => Promise,
create: (resource, params) => Promise,
update: (resource, params) => Promise,
updateMany: (resource, params) => Promise,
delete: (resource, params) => Promise,
deleteMany: (resource, params) => Promise,
}
我已经检查了代码,并期望看到每种方法的包装,这将添加catch
并在必要时触发重定向以登录。
相反,我不是这样,我想知道为什么以及如何在我的应用程序中正确解决此问题。
没有其他任何代码都不能说很多。需要更多东西,以便我们复制。 Promise
是否直接引用您正在使用的Promise库?具体答案完全取决于体系结构和您拥有的其他支持库。
这些是我们使用redux
,react-router-dom
采取的步骤>
PrivateRoute
包装所有需要私有的路由。它检查isLoggedIn
状态并返回页面组件或将用户重定向到/login
例如
// handle promise error private handleError = (errorMessage: Error) => { const message = JSON.parse(errorMessage.message); if (message.status === 401) { this.authentication.logout(); // triggers logout actions and destroy credentials } throw errorMessage; }
private destroyUserCredentials() { this.tokenResponse = null; this.tokenClaims = null; this.tokenHasExpired = true; this.accessToken = null; this.localStorage.removeItem(this.storageKey); }
// dispatch action to change redux store state appStore.dispatch(LogOutAction(token));
// Private route HOC export const PrivateRouteComponent = ({ component: Component, state: state, ...rest }) => { const renderComponent = (props) => { if (state.login.isLoggedIn) { return <Component {...props} />; } else { return <Redirect to='/login' />; } }; return ( <Route {...rest} render={renderComponent} /> ); }; // REF: pluralsight connect container function mapStateToProps(state, ownProps) { return { state: { login: state.authenticate } }; } export const PrivateRoute = connect(mapStateToProps)(PrivateRouteComponent);
// Route setup <Provider store={appStore}> <BrowserRouter> <Switch> <Route path='/login' component={LoginPage} /> <PrivateRoute path='/analytics' component={HomePage} /> <PrivateRoute path='/account' component={AccountPage} /> </Switch> </BrowserRouter> </Provider>