node.js - 使用嵌套路径时刷新时出现空白页

标签 node.js reactjs react-router web-config

我对 React 和 Webpack 还很陌生,我正在尝试使用 React-router-dom 在我的 Web 应用程序中进行路由。

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

我读了一些帖子,说要向我的 webpack.config.js 添加“publicPath”和“historyApiFallback: true”,但由于某种原因它仍然不起作用。不过,在添加之前,我收到了“无法获取网址”错误。

路由器.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>

显然这就是我所缺少的。

关于node.js - 使用嵌套路径时刷新时出现空白页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55880632/

相关文章:

react-router - 使用 React Router v4 和 react-transition-group v2 实现页面滑动动画

reactjs - 如何在 react 中隐藏登录和注册页面中的导航栏?

node.js - 使用 Visual Studio Task Runner Explorer 运行 gulpfile.js 时,如何调试它?

reactjs - 除一条特定路线外的所有路线的渲染组件

javascript - ./node_modules/express/lib/view.js 中的 Webpack 警告 关键依赖项 : the request of a dependency is an expression

javascript - 使用 Redux、React 和 react-router-dom 4.x 时从动态组件获取 ref

javascript - 状态解构仅适用于箭头函数类方法?

CSS 悬停在此 React 组件中的任何地方都不起作用

node.js - 如何解决使用服务帐户上传时 Google Drive 存储空间超出的问题

node.js - child_process.js 在哪里?