本文介绍了手动更改 URL 时反应路由不起作用 |反应路由器 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当通过 React-router 的 Link 组件更改 URL 时,我的路由工作正常.但是,如果我尝试在浏览器中手动更改 URL,则会遇到 404 错误.
下面是 routes.js 文件
从react"导入React;从react-router-dom"导入 {Route, Switch, NotFoundRoute};从./components/app.jsx"导入应用程序;从./components/homePage.jsx"导入主页;从./components/about/aboutPage.jsx"导入AboutPage;从./components/authors/authorPage.jsx"导入AuthorPage;从./components/authors/manageAuthorPage.jsx"导入ManageAuthorPage;从./components/notFoundPage.jsx"导入 NotFoundPage;无功路线 = (<应用程序><开关><Route name="home"精确路径="/" component={HomePage}/><Route name="authors" 精确路径="/authors" component={AuthorPage}/><Route name="addAuthor" 精确路径="/author" component={ManageAuthorPage}/><Route name="manageAuthor" path="/author/:id" component={ManageAuthorPage}/><Route name="about"精确路径="/about" component={AboutPage}/><路由组件={NotFoundPage}/></开关></应用程序>);导出默认路由;
包含 BrowserRouter 的 main.js 文件
从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-router-dom'导入{BrowserRouter};从'./routes.jsx'导入路由;从 './actions/initializeActions' 导入 InitializeActions;InitializeActions.initApp();ReactDOM.render(<BrowserRouter>{routes}</BrowserRouter>, document.getElementById('app'));
以及包含导航栏的 header.jsx 文件
从'react'导入React;从 'react-router-dom' 导入 {Link};类头扩展 React.Component {使成为() {返回 (<nav className="navbar navbar-default"><div className="容器流体"><Link to="/" className="navbar-brand"><img src="../../images/pluralsight-logo.png"/></链接><ul className="nav navbar-nav"><li><Link to="/">首页</Link></li><li><Link to="authors" ref={(comp) =>{ window.authorsTab=comp }}>作者</Link></li><li><Link to="about">关于</Link></li>
</nav>);}}导出默认标题;
Gulpfile.js
"使用严格";var gulp = require('gulp');var connect = require('gulp-connect');//运行本地开发服务器var open = require('gulp-open');//在浏览器中打开一个URLvar browserify = require('browserify');//捆绑JSvar reactify = require('reactify');//将 React JSX 转换为 JSvar source = require('vinyl-source-stream');//使用gulp的常规文本流var concat = require('gulp-concat');//连接文件var lint = require('gulp-eslint');//lint我们的js文件,包括jsxvar babelify = require("babelify");var browserSync = require("浏览器同步");变量配置 = {端口:9005,devBaseUrl: 'http://localhost',路径:{html: './src/*.html',js: './src/**/*.js*',图像:'./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'}}//启动本地开发服务器gulp.task('connect', function() {连接服务器({根:['dist'],端口:config.port,基础:config.devBaseUrl,实时加载:true});});//在浏览器中打开网址gulp.task('open', ['connect'], function() {gulp.src('dist/index.html').pipe(open({uri: config.devBaseUrl + ':' + config.port + '/'}));});//从'src'获取所有html文件,将它们打包并放入'dist'并重新加载服务器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"]}).捆().on('错误', 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('图像', function() {gulp.src(config.paths.images).pipe(gulp.dest(config.paths.dist + '/images')).pipe(connect.reload());});gulp.task('lint', function() {返回 gulp.src(config.paths.js).pipe(lint({configFile: 'eslint.config.json'})).pipe(lint.format());});//查看html文件的任何变化gulp.task('watch', function() {gulp.watch(config.paths.html, ['html']);gulp.watch(config.paths.js, ['js', 'lint']);gulp.watch(config.paths.css, ['css']);});//默认任务gulp.task('default', ['html', 'js', 'css', 'images', 'lint', 'open', 'watch']);
我尝试在多个来源上寻找解决方案,但每个人似乎都遵循与我类似的方法!请看一看.提前致谢:)
解决方案
使用 BrowserRouter
时,需要在 webpack 中添加 historApiFallback: true
.
将此添加到您的 webpack 配置
devServer: {historyApiFallback: 真,},
gulp 等价物类似于:
historyApiFallback = require('connect-history-api-fallback')//启动本地开发服务器gulp.task('connect', function() {连接服务器({根:['dist'],端口:config.port,基础:config.devBaseUrl,实时加载:真实,中间件:[ historyApiFallback() ]});});
参见这个更多详情链接
My Routing is working perfectly when URL is changed through Link component of React-router. However, if I try to change URL manually in browser, it hits 404 Error.
Below is the routes.js file
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;
The main.js file which contains BrowserRouter
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'));
and the header.jsx file which contains the nav bar
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']);
I've tried finding solutions on multiple sources, but everyone seems to follow the similar approach as mine !Please have a look. Thanks in advance :)
解决方案
When using BrowserRouter
, you need to add historApiFallback: true
in your webpack.
Add this to your webpack config
devServer: {
historyApiFallback: true,
},
The gulp equivalent would be something like:
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 link for more details
这篇关于手动更改 URL 时反应路由不起作用 |反应路由器 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!