Reputation: 67
I'm new in React. Have problem with react-router
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Index.tsx
<PrivateRoute path='/' component={Main} /> //without exact
<Route path='/signin' component={SignIn} />
PrivateRoute.tsx:
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
localStorage.getItem('authToken') ? (
<Component {...props} />
) : (
<Redirect
to={{ pathname: '/signin', state: { from: props.location } }}
/>
)
}
/>
)
Main.tsx:
const Main: FC = () => {
return (
<App>
<Switch>
{routes.map(route => (
<Route
key={route.path}
path={route.path}
exact={route.exact}
component={route.component}
/>
))}
</Switch>
</App>
)
}
routes.tsx:
export const routes = [
{
path: '/shop',
key: 'market',
component: props => (
<LazyLoad
component={React.lazy(() => import('./modules/shop/pages/Shop'))}
{...props}
/>
),
},
{
path: '/',
exact: true,
component: () => <div>main</div>,
skip: true,
},
]
App.tsx:
const App: FC<AppProps> = ({ children }) => {
const classes = useStyles()
const sidebarToggle = useState(false) // recommended: collapsed, setCollapsed
return (
<div className={classes.wrapper}>
<SidebarContext.Provider value={sidebarToggle}>
<Sidebar />
<main className={classes.main}>
<section className={classes.routeWrapper}>
<Nav />
<div className={classes.route}>{children}</div>
</section>
</main>
</SidebarContext.Provider>
</div>
)
}
So, problem is: without exact route i don't have this error, but when pass exact props to PrivateRoute, my shop component not works
Upvotes: 1
Views: 6133
Reputation: 492
exact
prop will get rid of nesting ability of Route
.For example, your Main
path is '/'
, so if you pass the exact
prop like this:
<PrivateRoute exact path='/' component={Main} />
Then you can't have a nested route inside Main
like /shop
, although your shop component is nested inside Main
.
componentDidMount
, componentDidUpdate
for class-based component, useEffect
hook for functional component)Please make sure there is no where you mutate the props or states directly (without condition) inside the life circle of component. For example, using setState
directly inside componentDidUpdate
will cause an infinite loop.
Upvotes: 1