react-router v4 子路由使用问题

初学者,不知道我的用法对不对。我用webpac-dev-server 打包完代码,我的想法是当我在访问localhost:8080/footer时,会加载Footer组件
访问localhost:8080/footer/cr时会加载CopyRight组件;

代码如下:

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <Router>
        <div>
          <Switch>
            //localhost:8080/footer 能访问
            <Route component={ComponentFooter} path='/footer'></Route>
          </Switch>
        </div>
      </Router>
    )
  }
}

class ComponentFooter extends React.Component {
  constructor() {
    super();
  }
  render() {
    return (
      <footer className={footerCss.miniFooter}>
        <h1>Footer</h1>
        //localhost:8080/footer/cr 访问出错
        <Route component={CopyRight} path={`${this.props.match.url}/cr`}></Route>
      </footer>
    )
  }
}
class CopyRight extends React.Component {
  constructor() {
    super();
  }
  render() {
    return (
        <a>copyright</a>
    )
  }
}

这段代码在访问localhost:8080/footer 时能路由到ComponentFooter组件
这段代码在访问localhost:8080/footer 时能路由到ComponentFooter组件
但是访问localhost:8080/footer/cr 时console中提示
× GET http://localhost:8080/footer/bundle.js
× GET http://localhost:8080/footer/bundle.js

webpack.config.js 如下:

var webpack = require('webpack');
var path = require('path');
module.exports = {
  context: __dirname+'/src',
  entry: "./js/root.js",
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['react','es2015'],
          }
        }
      },
      {
        test: /\.css$/,
        exclude: /(node_modules)/,
        use: [
          {loader:'style-loader'},
          {
            loader: 'css-loader',
            options: {
              modules: true,
              loacalIdentName: '[name]__[local]_[hash:base64:5]',
              sourceMap: true,
              importLoaders: 1
            }
          }
        ]
      },
      {
        test: /\.css$/,
        include: path.resolve(__dirname, './node_modules'),
        use: ['style-loader','css-loader']
      }
    ]
  },
  output: {
    path: __dirname+'/src',
    filename: 'bundle.js',
    publicPath: '/'
  }
}
阅读 2.6k
1 个回答

请把问题描述清楚,或者有清晰的截图。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题