为什么webpack构建后我的react-routing不起作用?

问题描述 投票:1回答:1

我做了一个简单的反应路由器。当我开发它时,我使用npm start命令启动了一个开发服务器。一切都在运作。但是当我使用命令npm run build(使用webpack)构建我的应用程序时,启动了一个简单的http服务器并转到/ add_project有一个404错误。我不知道为什么会这样。请帮忙!

这是代码:

App.js

imports...

render() {
    return (
        <Switch>
            <div>
                <Route exact path='/' component={Projects}/>
                <Route exact path='/add_project' component={AddProject} />
            </div>
        </Switch>
    );
}}

index.js

imports...

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

webpack.config.js

const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src',
  output: {
    filename: 'app.js',
    path: __dirname + '/dist'
  },
  devtool: 'source-map',
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  },
  plugins: [
    new HtmlPlugin({
      template: 'public/index.html'
    })
  ]
}

UPD:

的package.json

{
  "name": "Test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack -p --progress --config webpack.config.js",
    "dev-build": "webpack --progress -d --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress -d --config webpack.config.js --watch",
    "start": "react-scripts start"
  },
  "license": "MIT",
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.0.0",
    "css-loader": "^0.28.4",
    "eslint": "^4.18.1",
    "eslint-plugin-react": "^7.7.0",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "jquery": "^3.2.1",
    "react": "^15.6.1",
    "react-bootstrap": "^0.31.0",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "style-loader": "^0.18.2",
    "webpack": "^3.11.0"
  }
}

UPD2:

AddProject.js

import React, { Component } from 'react';

class AddProject extends Component {
  constructor()
  {
    super();
  }

  render() {
    return (
      <form className="form-horizontal">
        <input type="text" ref="title" className="input" />
        <input type="text" ref=""/>
      </form>
    );
  }
}

export default AddProject;
javascript reactjs webpack react-router
1个回答
0
投票

您已经使用'/'匹配精确路径,然后将其与/ add_project路由再次匹配。尝试改变

     <Route exact path='/add_project' component=
       {AddProject} />

      <Route path='/add_project' component=
       {AddProject} />

如果在父路由上设置了exact,则子路由不匹配,但404将按预期呈现

© www.soinside.com 2019 - 2024. All rights reserved.