Я пытаюсь отобразить мои компоненты внутри частных маршрутов, если пользователь авторизован. Но я продолжаю получать ошибку. Ошибка: превышена максимальная глубина обновления. Это может произойти, когда компонент повторно вызывает setState внутри componentWillUpdate или componentDidUpdate. React ограничивает количество вложенных обновлений, чтобы предотвратить бесконечные циклы.
Чтобы проверить, авторизован ли пользователь, я получаю токен из localStorage.
Закомментированная строка const authed = true предназначена для тестирования. и он работает.
Мой компонент Routes выглядит следующим образом:
import React from 'react';
import { Switch, Redirect, Route } from 'react-router-dom';
import { RouteWithLayout } from './components';
import { Main as MainLayout, Minimal as MinimalLayout} from './layouts';
import {
Dashboard as DashboardView,
ProductList as ProductListView,
UserList as UserListView,
Typography as TypographyView,
Icons as IconsView,
Account as AccountView,
Settings as SettingsView,
NotFound as NotFoundView,
Login as LoginView,
} from './views';
const Routes = () => {
const authed = !!localStorage.getItem('token');
//const authed = true;
return (
<Switch>
<RouteWithLayout authed={authed} component={LoginView} exact layout={MinimalLayout} path="/login" />
<Redirect exact from="/" to="/login" />
{/*authed={this.state.authed}*/}
<RouteWithLayout authed={authed} component={DashboardView} exact layout={MainLayout} path="/dashboard" />{' '}
<RouteWithLayout authed={authed} component={UserListView} exact layout={MainLayout} path="/users" />
<RouteWithLayout authed={authed} component={ProductListView} exact layout={MainLayout} path="/products" />
<RouteWithLayout authed={authed} component={TypographyView} exact layout={MainLayout} path="/typography" />
<RouteWithLayout authed={authed} component={IconsView} exact layout={MainLayout} path="/icons" />
<RouteWithLayout authed={authed} component={AccountView} exact layout={MainLayout} path="/account" />
<RouteWithLayout authed={authed} component={SettingsView} exact layout={MainLayout} path="/settings" />
<RouteWithLayout authed={authed} component={NotFoundView} exact layout={MinimalLayout} path="/not-found" />
<Redirect to="/not-found" />
</Switch>
);
};
export default Routes;
А мой RouteWithLayout выглядит так:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
const RouteWithLayout = props => {
const { authed, layout: Layout, component: Component, ...rest } = props;
return (
<Route
{...rest}
render={matchProps =>
authed === true ? (
<Layout>
<Component {...matchProps} />
</Layout>
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
};
RouteWithLayout.propTypes = {
authed: PropTypes.any,
component: PropTypes.any.isRequired,
layout: PropTypes.any.isRequired,
path: PropTypes.string,
props: PropTypes.any.isRequired,
};
export default RouteWithLayout;