React路由器无法获取任何指定的路由,除了根/

时间:2019-02-04 00:05:16

标签: reactjs webpack react-router

这是我的App.jsx,它首先安装到DOM:

import React, { Component } from 'react';
import Home from './Home.jsx';
import Representatives from './Representatives.jsx';
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";


export default class App extends Component {
  constructor() {
    super();
    this.state = {value: ''};
}

  render() {
    return (
        <Router>
            <div>
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/representatives" component={Representatives} />
                </Switch>
            </div> 
        </Router>
    )
  }
}

这是代表的组成部分:

import React, { Component } from 'react';


export default class Representatives extends Component {
  constructor() {
    super();
    this.state = {value: ''};
  }

  render() {
    return (
        <div>
          Hello World!
        </div>
    )
  }
}

它看起来就像我所看到的示例,我的webpack配置看起来就像我在类似文章中看到的其他示例。任何帮助将不胜感激,我花了4个多小时动脑筋

这是我的webpack配置:

const path = require('path');

const SRC_DIR = path.resolve(__dirname, './src');
const BUILD_DIR = path.resolve(__dirname, './public/');

module.exports = {
  mode: 'development',
  entry: path.resolve(SRC_DIR, 'index.jsx'),
  output: {
    filename: 'bundle.js',
    path: BUILD_DIR,
    publicPath: '/'
  },
  devServer: {
    historyApiFallback: true,
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: [/node_modules/],
        use: [{
          loader: 'babel-loader',
          options: { "presets": [
            "@babel/env",
            "@babel/react"
        ] }
        }],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ]
  }
}

我添加了historyApiFallback:true和publicPath:'/' 如另一篇文章所推荐。

这是index.js:

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App/App.jsx';

ReactDOM.render(<App />, document.getElementById('root'));

0 个答案:

没有答案