使用嵌套路径时刷新空白页

Blank page on refresh when using nested path

我对 React 和 webpack 很陌生,我正在尝试使用 react-router-dom 在我的网络应用程序中进行路由。

但是奇怪的事情发生了,当我将我的组件的路径定义为“/:guid”时,一切正常,但是如果我将它设置为“/users/:guid”,当我刷新页面。

我读了一些帖子说要将 'publicPath' 和 'historyApiFallback: true' 添加到我的 webpack.config.js,但由于某些原因它仍然不起作用。虽然,在添加它之前,我得到了 'cannot GET url' 错误。

Router.js:

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import UserInfo from '../Containers/UserInfo/UserInfo';
import Main from './Main/Main';

const Router = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path='/' component={Main} />
        <Route path='/users/:guid' component={UserInfo} />
      </Switch>
    </BrowserRouter>
  );
};

export default Router;

webpack.config.js:

const path = require('path');

const DIST_DIR = path.resolve(__dirname, 'dist');
const SRC_DIR = path.resolve(__dirname, 'src');

const config = {
  entry: `${SRC_DIR}/app/index.js`,
  output: {
    path: `${DIST_DIR}/`,
    filename: 'bundle.js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        include: SRC_DIR,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-2']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  devServer: {
    historyApiFallback: true
  }
};

module.exports = config;

好吧,经过更多研究,我找到了 this github webpack-dev-server 问题页面,该页面建议将 <base /> 添加到我的 "index.html" 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>React Training Project</title>
    <base href="/">
</head>
<body>
    <div id="app"></div>
    <script src="./bundle.js"></script>    
</body>
</html>

显然这就是我所缺少的。

这对我有用,谢谢

<base href="/">