首页 > 解决方案 > 即使 url 更改,路由组件也不会呈现。使用自定义 webpack

问题描述

代码库地址

下面是我的文件结构

在此处输入图像描述

和 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

在此处输入图像描述

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

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

和我的 index.js 在此处输入图像描述

标签: reactjsreact-routerreact-router-domhistoryreact-dom

解决方案


您需要添加exact到您的/路线,否则它将匹配以开头的任何内容,/并且由于它在 a 中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


推荐阅读