手动更改 URL 时 React 路由不起作用 |反应路由器 4

2023-12-11

当通过 React-router 的 Link 组件更改 URL 时,我的路由工作正常。但是,如果我尝试在浏览器中手动更改 URL,则会出现 404 错误。

下面是routes.js文件

import React from "react";
import {Route, Switch, NotFoundRoute} from 'react-router-dom';
import App from "./components/app.jsx";
import HomePage from "./components/homePage.jsx";
import AboutPage from "./components/about/aboutPage.jsx";
import AuthorPage from "./components/authors/authorPage.jsx";
import ManageAuthorPage from "./components/authors/manageAuthorPage.jsx";
import NotFoundPage from "./components/notFoundPage.jsx";

var routes = (
    <App>
        <Switch>
            <Route name="home" exact path="/" component={HomePage} />
            <Route name="authors" exact path="/authors" component={AuthorPage} />
            <Route name="addAuthor" exact path="/author" component={ManageAuthorPage} />
            <Route name="manageAuthor" path="/author/:id" component={ManageAuthorPage} />
            <Route name="about" exact path="/about" component={AboutPage} />
            <Route component={NotFoundPage} />
        </Switch>
    </App>
);

export default routes;

包含 BrowserRouter 的 main.js 文件

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import routes from './routes.jsx';
import InitializeActions from './actions/initializeActions';

InitializeActions.initApp();

ReactDOM.render(<BrowserRouter>{routes}</BrowserRouter>, document.getElementById('app'));

以及包含导航栏的 header.jsx 文件

import React from 'react';
import {Link} from 'react-router-dom';

class Header extends React.Component {
    render() {
        return (
            <nav className="navbar navbar-default">
                <div className="container-fluid">
                    <Link to="/" className="navbar-brand">
                        <img src="../../images/pluralsight-logo.png"/>
                    </Link>
                    <ul className="nav navbar-nav">
                        <li><Link to="/">Home</Link></li>
                        <li><Link to="authors" ref={(comp) => { window.authorsTab=comp }}>Authors</Link></li>
                        <li><Link to="about">About</Link></li>
                    </ul>
                </div>
            </nav>
        );
    }
}

export default Header;

Gulpfile.js

"use strict";

var gulp = require('gulp');
var connect = require('gulp-connect'); //Runs a local dev server
var open = require('gulp-open'); //Opens a URL in a web browser
var browserify = require('browserify'); //Bundle JS
var reactify = require('reactify'); //Transforms react JSX to JS
var source = require('vinyl-source-stream'); //Use-conventional text streams with gulp
var concat = require('gulp-concat'); //concatnates files
var lint = require('gulp-eslint'); //lint our js files including jsx
var babelify = require("babelify");
var browserSync = require("browser-sync");

var config = {
  port: 9005,
  devBaseUrl: 'http://localhost',
  paths: {
    html: './src/*.html',
    js: './src/**/*.js*',
    images: './src/images/*',
    css: [
      'node_modules/bootstrap/dist/css/bootstrap.min.css',
      'node_modules/bootstrap/dist/css/bootstrap-theme.min.css',
      './src/dependencies/*.css',
      'node_modules/toastr/build/toastr.css'
    ],
    dist: './dist',
    mainJs: './src/main.jsx'
  }
}

//start a local dev server
gulp.task('connect', function() {
  connect.server({
    root: ['dist'],
    port: config.port,
    base: config.devBaseUrl,
    livereload: true
  });
});

//opens the URL in browser
gulp.task('open', ['connect'], function() {
  gulp.src('dist/index.html')
    .pipe(open({uri: config.devBaseUrl + ':' + config.port + '/'}));
});

//get all the html files from 'src', bundle them and place inside 'dist' and reload the server
gulp.task('html', function() {
  gulp.src(config.paths.html)
    .pipe(gulp.dest(config.paths.dist))
    .pipe(connect.reload());
});

gulp.task('js', function() {
  browserify(config.paths.mainJs)
    .transform(babelify, {presets: ["es2015", "react"]})
    .bundle()
    .on('error', console.error.bind(console))
    .pipe(source('bundle.js'))
    .pipe(gulp.dest(config.paths.dist + '/scripts'))
    .pipe(connect.reload());
});

gulp.task('css', function() {
  gulp.src(config.paths.css)
    .pipe(concat('bundle.css'))
    .pipe(gulp.dest(config.paths.dist + '/css'));
});

gulp.task('images', function() {
  gulp.src(config.paths.images)
    .pipe(gulp.dest(config.paths.dist + '/images'))
    .pipe(connect.reload());
});

gulp.task('lint', function() {
  return gulp.src(config.paths.js)
    .pipe(lint({configFile: 'eslint.config.json'}))
    .pipe(lint.format());
});

//watch any changes in html files
gulp.task('watch', function() {
  gulp.watch(config.paths.html, ['html']);
  gulp.watch(config.paths.js, ['js', 'lint']);  
  gulp.watch(config.paths.css, ['css']);  
});

//the default task
gulp.task('default', ['html', 'js', 'css', 'images', 'lint', 'open', 'watch']);

我尝试在多个来源寻找解决方案,但每个人似乎都遵循与我类似的方法! 请看一看。提前致谢 :)


使用时BrowserRouter,你需要添加historApiFallback: true在你的网页包中。

将其添加到您的 webpack 配置中

devServer: {
    historyApiFallback: true,
  },

gulp 等效项类似于:

historyApiFallback = require('connect-history-api-fallback')


//start a local dev server
gulp.task('connect', function() {
  connect.server({
    root: ['dist'],
    port: config.port,
    base: config.devBaseUrl,
    livereload: true,
    middleware: [ historyApiFallback() ]
  });
});

See this链接了解更多详情

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

手动更改 URL 时 React 路由不起作用 |反应路由器 4 的相关文章

随机推荐

  • 按组前缀旋转更长的时间

    我需要按列字符串前缀分组更长的时间 下面的玩具示例有两个组 A 和 B 但我需要一个针对任意数量的前缀组的通用 tidyverse 解决方案 toy df set seed 1 df lt data table date rep seq a
  • 尝试仅解析 RSS 源中的图像

    首先 我是一个php新手 我已经查看了问题和解决方案here 然而 对于我的需要 解析对各种文章的深入程度还不够 我的 rss feed 的一小部分内容如下
  • Angular 4:如何包含 Bootstrap?

    我是一名后端开发人员 我只是在玩 Angular4 所以我做了这个安装教程 https www youtube com watch v cdlbFEsAGXo 鉴于此 我如何向应用程序添加引导程序 以便我可以使用 container flu
  • 当 TFramedTransport 打开时,thrift 中的 TNonblockingServer 崩溃

    我一直在尝试用 C 实现一个 Thrift 服务器来与 Python 客户端进行通信 这是我的代码 C 服务器 shared ptr
  • 使用 PHP 克隆 MySQL 到 MySQL

    有人知道一个 PHP 脚本可以将整个 MySQL 数据库克隆到另一台服务器上的另一个数据库吗 作为一种备份 您可以运行 PHP 脚本 例如使用 exec 或 system 调用 例如 mysqldump q C databases myda
  • 删除重复行

    我有一张看起来像这样的桌子 Table1 Id Name 如何编写一个查询来删除所有具有重复名称的行 但保留具有较低 ID 的行 如果您使用的是 SQL Server 2005 或更高版本 With Dups As Select Id Na
  • 仅在使用 Vue 悬停时显示截断的文本

    我尝试过这样的
  • QML 渲染器中的文本在不同平台上有所不同

    我发现不同平台之间的文本呈现不一致 左上角的图像是在 android 中生成的 正如红色引导线所示 它在斜体样式的垂直位置和角度方面与 参考 窗口输出不同 Rectangle width 100 height 50 color grey T
  • 将数组合并为对象数组 JavaScript

    我这里有一个数组 var array firstName Nork lastName James age 22 position writer firstName James lastName Rodel age 25 position p
  • 优化此核心数据请求

    我在核心数据中有一个名为 MusicInterest 的实体 我必须一次添加 5000 个左右 我当前的流程是查询 MusicInterest 是否已存在 如果不存在则创建一个新的 看来这需要去商店 5000 次才能查看每个标题是否存在 当
  • 前瞻之前的惰性正则表达式:不适用于“.+?”

    我正在使用 VS 代码 我想选择所有匹配项italics前 term 不幸的是 VS code 还不支持lookbehind 所以我对第一个 图案 term 内容 Pivot Row term This is another term Pi
  • 带有 logback 的异步 DBAppender

    我正在开发一个使用 logback 进行日志记录的应用程序 我使用 logback DBAppender 将日志插入数据库 一切对我来说都很好 我能够将日志插入数据库并查看日志 我用 200 行日志代码进行了一些测试 并测量了这 200 条
  • 类型后跟 _t(下划线-t)代表什么?

    这似乎是一个简单的问题 但我无法通过 Stack Overflow 搜索或 Google 找到它 type 后跟 a 是什么意思 t意思是 例如 int t anInt 我在 C 代码中经常看到它与硬件密切相关 我不禁认为它们是相关的 正如
  • 查找两个数组之间的共同最小值

    我正在解决 Javascript 中的一个问题 寻找两个数组之间的共同最小值 然而 我被告知这可能不适用于某些值 有什么问题吗 function cmp a b return a b function findMinimum A B var
  • 在 DQL 中使用 SHA1 的任何方式

    下面的 DQL 会生成错误 Syntax Error line 0 col 42 Error Expected known function got sha1 有什么办法可以使用SHA1吗 public function findIdByD
  • 使用邻接表创建图

    include
  • C#:即使使用 httpclient 发送 CSRF 令牌后也会收到 403

    我正在尝试从我的 UWP 应用程序将有效负载发布到我们的后端系统 为此 我首先执行 GET 来获取 CSRF 令牌 然后将其添加到 POST 请求的标头中 发帖时 我仍然收到 403 Forbidden 错误 我正在与 Insomnia R
  • R:使 Ryacas 包在 Windows 上运行时遇到问题

    我正在尝试使用该包Ryacas in R 这是发生了什么 gt install packages Ryacas Please select a CRAN mirror for use in this session trying URL h
  • ASP.NET高效聊天应用方法

    我有与 SQL SERVER 2005 2008 连接的 ASP NET 4 Web 应用程序 我想为我的应用程序用户添加 聊天 功能 假设该功能将从头开始构建 最有效的合理方法是什么 Using WCF每 3 秒有一个 Javascrip
  • 手动更改 URL 时 React 路由不起作用 |反应路由器 4

    当通过 React router 的 Link 组件更改 URL 时 我的路由工作正常 但是 如果我尝试在浏览器中手动更改 URL 则会出现 404 错误 下面是routes js文件 import React from react imp