react-router-dom BrowserRouter 不导航到具有多个 url 参数的路径 [英] react-router-dom BrowserRouter not navigating to paths with more than one url parameter

查看:87
本文介绍了react-router-dom BrowserRouter 不导航到具有多个 url 参数的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,当使用 react-router-dom@4.2.2 时,我无法导航到路径大于 1 部分的路由:此外,这是Github 链接到我遇到此问题的存储库.

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

[OK] 从 ./dist 提供静态文件[OK] 使用回退文件 index.html[OK] 监听 http://localhost:8080----------------------------------------------[确定] GET/accountSetup[确定] GET/bundle.js[确定] GET/accountSetup/123[ER] 获取/accountSetup/bundle.js

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

似乎是关于使用动态路由的 BrowserRouter 与使用静态路由的 HashRouter.

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

package.json:

<代码>{"name": "react-webpack4-typescript-skeleton",版本":1.0.0","description": "使用 Webpack 4 和 Typescript 的 React 应用程序","main": "index.tsx",脚本":{"start": "webpack-dev-server --open --mode 开发","prestart": "npm 运行测试","build:prod": "webpack --mode production --config webpack.config.js","lint": "tslint 'src/**/*.{ts,tsx}'","test": "开玩笑","pretest": "npm 运行 lint","build:docker": "docker-compose up --build -d"},关键词":[反应","Webpack 4",打字稿"],"author": "Shawn Choleva","许可证": "麻省理工学院",开发依赖":{"@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","文件加载器": "^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","打字稿": "^2.7.2","url-loader": "^1.0.1","webpack": "^4.2.0","webpack-cli": "^2.0.13","webpack-dev-server": "^3.1.1"},依赖关系":{"少": "^3.0.1",反应":^ 16.2.0","react-dom": "^16.2.0","react-redux": "^5.0.7","react-router-dom": "^4.2.2","redux": "^3.7.2"},开玩笑":{转换": {"^.+\\.tsx?$": "ts-jest"},"testRegex": "(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",模块文件扩展名":["ts","tsx","js","jsx","json",节点"]}}

webpack.config.js:

const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin')常量配置 = {条目:'./src/index.tsx',输出: {文件名:'bundle.js',路径:path.resolve(__dirname, 'dist')},模块: {规则: [{测试:/\.tsx?$/,使用:'ts-loader',排除:/node_modules/},{测试:/\.less$/,用: [{装载机:风格装载机"},{加载器:css-加载器",选项: {源地图:真实,模块:真实,localIdentName: '[local]___[hash:base64:5]'}},{装载机:少装载机"}]},{测试:/\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,使用:'url-loader'},{测试:/\.(png|jp(e*)g|svg)$/,用: [{装载机:网址装载机",选项: {限制:10000,name: '图像/[hash]-[name].[ext]',},}]}]},解决: {扩展名:['.ts'、'.tsx'、'.js']},插件: [新的 HtmlWebpackPlugin({title: '应用程序名称',模板:path.join(__dirname, 'src/index.html')})],开发工具:'内联源映射',开发服务器:{压缩:真的,端口:8080,historyApiFallback: 真,contentBase: path.resolve(__dirname),公共路径:'/',}};module.exports = config;

解决方案

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

输出:{文件名:'bundle.js',路径:path.resolve(__dirname, 'dist'),publicPath: '/' <-- 添加了这个},

I am having an issue where I am not able to navigate to Routes with paths greater than 1 section like so when using react-router-dom@4.2.2: In addition, this is the Github link to the repo where I am having this issue.

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>
        );
    }
}

So I noticed this is only working when I use HashRouter instead of BrowserRouter. So that led me to think it may be how I am serving the application via webpack-dev-server@3.1.1. So I saw that I had to add historyApiFallback property to my devServer properties object using webpack@4.2.0 like so:

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

And then I run the application through a npm script in my package.json that looks like this:

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

So when I navigate to localhost:5000/accountSetup/123 I get the following error in the console:

I have also tried to serve this with the http-server-spa package and noticed the following log when navigating:

[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

It seems like it is adding the prefix in the url of the last route parameter to the route loading bundle.js. So you can see when I navigated to accountSetup, it just referenced bundle.js because it the last segment in the url. But when I add multiple segments, it seems to append the prior segments from localhost to the last segment, to the path of bundle.js

EDIT:

Seems to be something in regards to BrowserRouter using dynamic routing vs HashRouter using static routing.

This is my full package.json and webpack.config.js files

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;

解决方案

I think I have found the issue. The publicPath was missing in your webpack configuration. Here is the updated output config:

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

这篇关于react-router-dom BrowserRouter 不导航到具有多个 url 参数的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆