React Route不适用于嵌套URL

时间:2019-02-13 21:06:04

标签: reactjs webpack react-router

我正在尝试使用一个根据URL路由不同组件的开关。该URl应该可以嵌套,例如courses/:cid/assignments/:aid

这是我的Switch的外观:

<Switch>
  <Route path='/courses/:cid/assignments/:aid' component={Assignment} />
  <Route exact path="/" component={Home} />
</Switch>

该应用运行良好:我可以访问主页。但是,当我访问例如courses/1/assignments/20时,出现以下错误:

Loading failed for the <script> with source “http://localhost:8081/courses/1/assignmentsets/bundle.js”.

我摸索了一下路径,只是想看看哪里出错了,结果是:

<Switch>
  <Route path='/courses/:cid/assignments/:aid' component={Assignments} /> // Does not work
  <Route path="/courses/randomnestedurl" component={Assignments} /> // Does not work
  <Route path="/courses" component={Assignments} /> // Works fine
  <Route path="/:aid" component={Assignments} /> // Works fine
  <Route exact path="/" component={Home} /> // Works fine
</Switch>

有人知道什么可能是错的吗?我的webpack有东西吗?我缺少某些设置吗?

如果需要提供更多代码,请告诉我需要应用程序的哪些部分。

编辑:这是我的webpack.config.js:

const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const APP_PATH = path.resolve(__dirname, 'src');

module.exports = {
  entry: APP_PATH,

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, '/dist'),
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.json']
  },

  module: {
    rules: [
      { test: /\.(ts|js)x?$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test:/\.(s*)css$/, use:['style-loader','css-loader', 'sass-loader'] },
    ],
  },

  devServer: {
    historyApiFallback: true,
    proxy: {
      '/api': {
          target: 'http://localhost:8080',
          secure: false
      }
  }
  },

  plugins: [
    new HtmlWebpackPlugin({ inject: true, template: path.join(APP_PATH, 'index.html') }),
    new ForkTsCheckerWebpackPlugin(),
  ]`enter code here`
};

2 个答案:

答案 0 :(得分:1)

好像您在以下站点中拥有脚本一样:

<script src="bundle.js"></script>

将其编辑为(/在文件名之前):

<script src="/bundle.js"></script>

答案 1 :(得分:1)

浏览器正在尝试从bundle.js加载http://localhost:8081/courses/1/assignmentsets/bundle.js表示bundle.js的写法是bundle.js而不是/bundle.js属性中的src index.html文件中的脚本标签。

要解决此问题,您可以在Webpack配置中添加一个publicPath

module.exports = {
  entry: APP_PATH,

  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, '/dist'),
    publicPath: '/'
  },

  // ...
}