即使 url 更改,路由组件也不会呈现。使用自定义 webpack

时间:2020-12-23 15:59:42

标签: reactjs react-router react-router-dom history react-dom

code repository url

下面是我的文件结构

enter image description here

和 webpack.config.js 看起来像下面这样

const path = require("path");

const HtmlWebPackPlugin = require("html-webpack-plugin");

const entryPoint = path.join(__dirname, "src", "index.js");

module.exports = {
  entry: entryPoint,
  output: {
    path: path.join(__dirname, "public"),
    filename: "bundle.js",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: path.join(__dirname, "public", "index.html"),
      filename: "./index.html",
    }),
  ],
  devServer: {
    contentBase: path.join(__dirname, "public"),
    historyApiFallback: true,
    // publicPath: "/dist/",
  },
  devtool: "source-map",
  stats: {
    errorDetails: true,
  },
};

我不知道为什么它仍然不起作用,尽管我已经给了 historyApiFallback

下面是我的 app.js

enter image description here

当我点击 /home 路线时,内容没有改变。

谁能解释一下我还有什么要补充的

和我的 index.js enter image description here

1 个答案:

答案 0 :(得分:1)

您需要将 exact 添加到您的 / 路线,否则它将匹配以 / 开头的任何内容,并且由于它在 Switch 中,因此它将是唯一一个匹配匹配。

    <Switch>
      <Route exact path="/" component={() => <div>i am in home</div>} />
      <Route exact path="/home" component={() => <div> i am user</div>} />
    </Switch>

如果 url 未参数化,我也会将 exact 添加到 /home

见:https://reactrouter.com/web/api/Route/exact-bool