在页面http://localhost/about上刷新时未找到以下代码报告404 . 但是如果将browserHistory更改为hashHistory,它可以正常工作 .
这是我的js文件 .
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory, hashHistory } from 'react-router';
import $ from 'jquery';
class App extends Component {
render() {
return (
<div>
<h1>APP!</h1>
<Link to="/about">/about</Link>
{this.props.children}
</div>
)
}
}
class About extends React.Component {
render() {
return (
<div>
<h2>About 33</h2>
</div>
)
}
}
var routes = (
<Router history={hashHistory}>
<Route path="/" component={App} />
<Route path="/about" component={About} />
<Route path="/wealth" component={WealthExpectation} />
</Router>
)
$(document).ready(function() {ReactDOM.render(routes, document.getElementById("hello"))});
和html文件 .
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello React</title>
<script type="text/javascript" src="/static/js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="/static/js/script.js"></script>
<!-- build:css -->
<link rel="stylesheet" type="text/css" href="/static/bower_modules/c3/c3.min.css">
<!-- endbuild -->
</head>
<body>
<div id="hello">a</div>
<div id="world"></div>
</body>
</html>
我已经阅读了react-router v2.0 browserHistory not working和React-router urls don't work when refreshing or writting manually上的问题 . 对于第一个,我've already set the path to absolute path, but still not working. For the second one, I tried to import express but failed ('未捕获TypeError:无法读取未定义的属性'prototype'') .
4 回答
要扩展Phi Nguyen 's answer the reason hashHistory works and browserHistory fails is because hashHistory is sort of a ' hack'或解决方法,以允许您的应用在没有浏览器注意的情况下操作URL并向您的服务器发送
GET
请求 . 基本上哈希之后的所有内容都会被忽略 .browserHistory通常是首选,因为它看起来更好,但您不再获得散列解决方法,并且您需要其他方法来阻止您的浏览器尝试向您的服务器发送请求 . 如果您使用webpack,则有一种简单的方法可以使所有请求回退到单个请求 . 例如:
GET
到http://localhost:8080/和GET
到http://localhost:8080/about都会回退到http://localhost:8080/并且react-router会处理/ about . (这就是你能够导航到/关于罚款的原因,但是如果你刷新就会得到一个404
错误,那么你发送一个GET
到/关于服务器上不存在的那个)为此,您需要实现名为history api fallback的webpack功能 . 有两种方法可以做到这一点 .
在react-router docs / tutorial中,您可以将
start
脚本设置为如下所示:对于有此错误的人来说,--history-api-fallback是重要的部分 .
或者您可以更改您的
webpack.config.js
文件以在您的开发服务器上处理此问题 .另一种简单且低成本的方法是让Apache将任何请求映射到您的React应用程序 . 例如:
http://localhost/about
内部通过http://localhost/[my-own-html-file.html]
例如,如果我们的React应用程序从
index.html
开始,则需要在React应用程序上创建.htaccess
文件并插入以下代码:顺便说一句,这个HTACCESS代码改编自Drupal 8:https://github.com/drupal/drupal/blob/8.2.x/.htaccess
使用
browser history
时,服务器不知道如何处理仅在浏览器中更改的URL . 这个tutorial将教你如何删除url中的#
并使browser history
工作 .为了使用browserHistory,您需要实现一个快速服务器来处理真实的URL . hashHistory不需要快速服务器 .
请查看以下指南:
https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md