react-router-dom BrowserRouter无法导航到具有多个url参数的路径

时间:2018-04-13 20:20:34

标签: reactjs webpack webpack-dev-server react-router-dom webpack-4

我遇到的问题是,当使用react-router-dom@4.2.2时,我无法导航到路径大于1的路径,这样就是这样的问题:此外,这是我在解决此问题的回购的Github链接

https://github.com/ShawnCholeva/React-Typescript-Webpack4-Router

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
//All routes work if I use HashRouter here instead of BrowserRouter

class App extends Component {
    render() {
        return (
            <Router>
                <Switch>
                    <Route exact path='/' component={ Login }/> <--- Works
                    <Route exact path='/accountSetup/:guid?' component={ AccountSetup }/> 
                    ^-- Above works when just '/accountSetup' but fails when I do '/accountSetup/123'
                    <Route component={ NotFound } /> <--- Works
                </Switch>
            </Router>
        );
    }
}

所以我注意到这只在我使用HashRouter而不是BrowserRouter时才有效。因此,我认为可能是我通过webpack-dev-server@3.1.1提供应用程序的方式。所以我看到我必须使用webpack@4.2.0将historyApiFallback属性添加到我的devServer属性对象中,如下所示:

devServer: {
    compress: true,
    port: 8080,
    historyApiFallback: true,
    contentBase: path.resolve(__dirname),
    publicPath: '/',
}

然后我通过我的package.json中的npm脚本运行应用程序,如下所示:

"start": "webpack-dev-server --open --mode development"

因此,当我导航到localhost:5000 / accountSetup / 123时,我在控制台中收到以下错误:

enter image description here

我还尝试使用http-server-spa包提供此功能,并在导航时注意到以下日志:

[OK] Serving static files from ./dist
[OK] Using the fallback file index.html
[OK] Listening on http://localhost:8080
----------------------------------------------
[OK] GET /accountSetup
[OK] GET /bundle.js
[OK] GET /accountSetup/123
[ER] GET /accountSetup/bundle.js

似乎是将最后一个路由参数的url中的前缀添加到路由加载bundle.js中。所以你可以看到当我导航到accountSetup时,它只是引用了bundle.js,因为它是url中的最后一个段。但是当我添加多个段时,它似乎将从localhost到最后一个段的先前段附加到bundle.js的路径

编辑:

似乎是使用动态路由的BrowserRouter与使用静态路由的HashRouter相关的事情。

这是我的完整package.json和webpack.config.js文件

的package.json:

{
  "name": "react-webpack4-typescript-skeleton",
  "version": "1.0.0",
  "description": "React application using Webpack 4 and Typescript",
  "main": "index.tsx",
  "scripts": {
    "start": "webpack-dev-server --open --mode development",
    "prestart": "npm run test",
    "build:prod": "webpack --mode production --config webpack.config.js",
    "lint": "tslint 'src/**/*.{ts,tsx}'",
    "test": "jest",
    "pretest": "npm run lint",
    "build:docker": "docker-compose up --build -d"
  },
  "keywords": [
    "React",
    "Webpack 4",
    "Typescript"
  ],
  "author": "Shawn Choleva",
  "license": "MIT",
  "devDependencies": {
    "@types/jest": "^22.2.2",
    "@types/react": "^16.0.41",
    "@types/react-dom": "^16.0.4",
    "@types/react-redux": "^5.0.15",
    "@types/react-router-dom": "^4.2.5",
    "@types/redux": "^3.6.0",
    "@types/webpack": "^4.1.2",
    "@types/webpack-dev-server": "^2.9.4",
    "css-loader": "^0.28.11",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.1.0",
    "jest": "^22.4.3",
    "less-loader": "^4.1.0",
    "style-loader": "^0.20.3",
    "ts-jest": "^22.4.2",
    "ts-loader": "^4.1.0",
    "tslint": "^5.9.1",
    "tslint-react": "^3.5.1",
    "typescript": "^2.7.2",
    "url-loader": "^1.0.1",
    "webpack": "^4.2.0",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.1"
  },
  "dependencies": {
    "less": "^3.0.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.7",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2"
  },
  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

const config = {
  entry: './src/index.tsx',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
              modules: true,
              localIdentName: '[local]___[hash:base64:5]'
             }
          },
          {
            loader: "less-loader"
          }
        ]
      },
      { 
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use:'url-loader' 
      },
      { 
        test: /\.(png|jp(e*)g|svg)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: 'images/[hash]-[name].[ext]',
            },
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [ '.ts', '.tsx', '.js' ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        title: 'Application Name',
        template: path.join(__dirname, 'src/index.html')
    })
  ],
  devtool: 'inline-source-map',
  devServer: {
    compress: true,
    port: 8080,
    historyApiFallback: true,
    contentBase: path.resolve(__dirname),
    publicPath: '/',
  }
};

module.exports = config;

2 个答案:

答案 0 :(得分:5)

我想我已经找到了这个问题。您的webpack配置中缺少publicPath。这是更新的输出配置:

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

答案 1 :(得分:1)

看起来你正在尝试制作嵌套路线。但是在ReactRouter v4中你指出使用动态路由嵌套路由应该嵌套在组件内部。您应该添加AccountSetup渲染方法的含义。

render(){
 //...
  <Route
    path={match.url + '/test'}
    component={Test}
  />
// ...
}

阅读docs中有关嵌套路线的更多信息。这是一个live example 如果您确实想要使用静态路由,可以try this