React-router用browserHistory页面刷新问题

#1
import React from 'react'
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'
import App from '../component/App'
import Home from '../component/Home'
import About from '../component/About'

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <IndexRoute component={Home} />
      <Route path='about' component={About} />
      <Route path='home' component={Home} />
    </Route>
  </Router>,
  document.getElementById('app')
)

刷新后:

请问使用browserHistory,页面刷新后还可以加载about组件,要怎么处理才好,谢谢~

#2

版本为:“react-router”: “^2.3.0”

#3

用browserHistory需要服务器Rewrites设置,否则刷新会找不到对应链接

#4

原来如此,谢谢你的提醒

#5

可以具体谈谈么?

#6

这个需要服务器端进行设置,因为服务器并不知道如何处理 url ,而且实际上 /about 在服务器端并没有物理文件或文件夹,所以要在服务器端把所有非 / 的路径请求 rewrite 映射到 / 上,而且浏览器端的地址不会改变。

所以,当你请求 /about 的时候,其实显示的是 / 目录下的内容,即使如此,浏览器的地址还是 /about ,所以 React 在初始化的时候还是能够根据 url 来正确的加载内容。

#7

这样会把routes的配置说服务器设置耦合起来,是不是一般不太建议使用browserHistory啊?

#8

我的package.json:

start": “webpack-dev-server --progress --colors --hot --content-base ./server/public --history-api-fallback --config ./webpack.config.js”,

加 --history-api-fallback这个参数即可。

1 Like
#9

如果你使用的是 node 作为服务器,将服务器端的路由最下面的配置为 * 。

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.use('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})

楼上使用 webpack 插件 也可以。

react-router 官方文档有说明这类问题 点击这里查看官方文档说明

#10

请问是怎么解决的呢?