React Router 子路由未显示

React Router Subroutes not showing

我正在使用 react-router-dom 在我的应用程序中进行路由。我在显示子路线时遇到困难。我有 2 条路线,localhost:8080/ 和 localhost:8080/posts/new。 localhost:8080/ 路线按预期工作。如果我把第二条路由改成/posts,比如localhost:8080/posts,那么它就可以正常显示了。我在 '/' 路由上使用了 exact prop,并在 webpack devServer 中设置了以下配置:{historyApiFallback: true},但这并不能解决问题。

我在控制台中收到 2 个错误:

错误 #1: GET http://localhost:8080/posts/bundle.js 404 (Not Found).

Error #2: Refused to execute script from 'http://localhost:8080/posts/bundle.js' 因为它的 MIME 类型 ('text/html') 不可执行,并且启用了严格的 MIME 类型检查。

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import reduxPromise from 'redux-promise';

import reducers from './reducers/index';
import PostsIndex from './components/posts-index';
import PostsNew from './components/posts-new';

const createStoreWithMiddleware = applyMiddleware(reduxPromise)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
      <Router>
        <Switch>
            <Route exact path="/" component={PostsIndex} />
            <Route path="/posts/new" component={PostsNew} />
        </Switch>
      </Router>
   </Provider>, document.querySelector('.container'));

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename:'bundle.js'
    },
    module: {
        rules: [
            {
                exclude: /node_modules/,
                test: /\.js$/,
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: './src/index.html',
            filename: 'index.html'
        })
    ],
    devServer: {
        historyApiFallback: true
    }
}

感谢任何帮助。

HTMLWebpackPluginoutput.publicPath 添加到它注入到 HTML 文件中的所有资产。如果没有 publicPath,JavaScript 文件将被注入为 <script src="bundle.js"></script>。因此,bundle.js 将相对于您当前的 url 加载,这不是您想要的。

publicPath 设置为 /,它应该会按预期工作。

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename:'bundle.js',
        publicPath: '/'
    },
    // ...
}