xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

React Router Bug

React Router Bug

Uncaught Error: Invariant failed: You should not use <Switch> outside a <Router>

Error: Error: Invariant failed: You should not use outside a

The above error occurred in the component: in AppContainer (created by HotExportedApp)

react-dom.development.js?f8c1:19527 The above error occurred in the <Context.Consumer> component: in Switch (created by App)

solutions

  1. 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);

  1. 最外层 add <Router> outside <Switch>

<Router> !== <Route>

<Router>
    <Switch>
         <Route path="/login" component={AsyncLogin} />
    </Switch>
</Router>

refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-04-06 23:30  xgqfrms  阅读(674)  评论(8编辑  收藏  举报