Webpack React错误:不应在<Router>外使用<Switch>

时间:2019-11-02 03:56:37

标签: reactjs webpack react-router babel react-router-dom

所以我试图用我的React应用程序设置服务器端渲染,到目前为止,我已经解决了所有问题,但是经过几天的尝试,我遇到了无法解决的问题。

我使用的是最新的内容,并且遇到此错误:Error: Invariant failed: You should not use <Switch> outside a <Router>

以下是React应用的索引

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter  } from 'react-router-dom';

const SSR = (
    <BrowserRouter>
        <App/>
    </BrowserRouter>
);

if(typeof document === "undefined") {
    module.exports = SSR;
} else {
    ReactDOM.hydrate(SSR, document.getElementById("app"));
}

和组件

import React from 'react';
import { Route, Switch } from 'react-router-dom'

import Home from './components/index'

const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
        <React.Fragment>
            <Navbar/>
            <Component {...props}/>
        </React.Fragment>
    )}/>
)

export default class App extends React.Component {
    render() {    
        return (
            <Switch>
                <NavRoute exact={true} path="/" component={Home}/>
            </Switch>
        );
    }
}

还有我的webpack配置

const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');

module.exports = [
    {
        entry: {
            client: './server/index.js',
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: "[name].js",
            publicPath: '/',
        },
        target: 'node',
        externals: [nodeExternals()],
        module: {
            rules: [
                { test: /\.jsx?/, loader: "babel-loader"}
            ]   
        },

    },
    {
        entry: {
            bundle: './src/App.js'
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: "[name].js",
            publicPath: '/',
            libraryTarget: "umd",
            globalObject: "this",
        },
        module: {
            rules: [
                { test: /\.jsx?/, loader: "babel-loader"}
            ]   
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env.BROWSER': JSON.stringify(true),
            }),
        ]
    }
]

感谢您的帮助,如果您错过了任何信息,请告诉我。

0 个答案:

没有答案