React Router Bug
Uncaught Error: Invariant failed: You should not use <Switch> outside a <Router>
Error: Error: Invariant failed: You should not use
The above error occurred in the
react-dom.development.js?f8c1:19527 The above error occurred in the <Context.Consumer> component: in Switch (created by App)
solutions
- using
react-router-dom
&<BrowserRouter>
import React, {lazy, Suspense, useEffect} from 'react';
// import { Switch, Route, Redirect } from 'react-router';
import {
// Switch,
// Route,
// Redirect,
} from 'react-router';
import {
BrowserRouter,
Switch,
Route,
Redirect,
} from 'react-router-dom';
import { hot, setConfig } from 'react-hot-loader';
import MyLoading from '@/components/MyLoading';
import Util from '@/utils';
setConfig({
showReactDomPatchNotification: false
});
const AsyncHome = lazy(() => import('@/views/home'));
const AsyncLogin = lazy(() => import('@/views/login'));
function App (props) {
useEffect(() => {
if (!Util.isAuth()) {
Util.setLocalItem('token', '');
}
}, []);
return (
<Suspense fallback={<MyLoading />}>
<BrowserRouter>
<Switch>
<Route path="/login" component={AsyncLogin} />
<Route render={props => (
Util.getLocalItem('token') ?
(<AsyncHome/>) :
(<Redirect to={{ pathname: '/login', state: { from: props.location } }} />)
)}/>
</Switch>
</BrowserRouter>
</Suspense>
);
}
export default hot(module)(App);
- 最外层 add
<Router>
outside<Switch>
<Router>
!==<Route>
<Router>
<Switch>
<Route path="/login" component={AsyncLogin} />
</Switch>
</Router>
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!