【问题标题】:Route Component dose not render even though url changes. with custom webpack即使 url 更改,路由组件也不会呈现。使用自定义 webpack
【发布时间】:2021-04-02 06:01:00
【问题描述】:

code repository url

下面是我的文件结构

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

【问题讨论】:

  • 也许我的问题听起来很傻,但你有没有把你的App 包裹在BrowserRouter 中?
  • 是的。我已经编辑了问题
  • 为每条路由添加exact prop。
  • 我认为你需要使用render 而不是component: reactrouter.com/web/api/Route/render-func

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


【解决方案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>

如果网址没有参数化,我也会将exact 添加到/home

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

【讨论】:

  • 在 react-router-dom v4 的早期版本中,不需要为两条路由都添加确切的内容。如果可以添加到以前可以工作的单独家中
  • @ShivaSai 如果您知道您只需要确切的路线,则使用exact 会更安全,因此您以后添加/home/"id 路线时不必调试。此外,当不使用exact 时,Route 的顺序变得很重要。
猜你喜欢
  • 2016-12-26
  • 2021-11-06
  • 1970-01-01
  • 2020-05-06
  • 2014-06-22
  • 1970-01-01
  • 2021-10-07
  • 2022-10-13
  • 2021-09-27
相关资源
最近更新 更多