react-router和History简介
react-router
react-router是为react专门构建的一个路由插件,他可以帮助我们实现简单的单页应用效果,学习react的人,避免不了学习react-router的用法。
History
history 一个管理js应用session会话历史的js库。它将不同环境(浏览器,node...)的变量统一成了一个简易的API来管理历史堆栈、导航、确认跳转、以及sessions间的持续状态。
History基本 使用
import { createHistory } from 'history'
const history = createHistory()
// 当前的地址
const location = history.getCurrentLocation()
// 监听当前的地址变换
const unlisten = history.listen(location => {
console.log(location.pathname)
})
// 将新入口放入历史堆栈
history.push({
pathname: '/the/path',
search: '?a=query',
// 一些不存在url参数上面的当前url的状态值
state: { the: 'state' }
})
// When you're finished, stop the listener
unlisten()
location
你也可以使用 history对象来的方法来改变当前的location:
push(location)
replace(location)
go(n)
goBack()
goForward()
一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。
location对象包括:
pathname 同window.location.pathname
search 同window.location.search
state 一个捆绑在这个地址上的object对象
action PUSH, REPLACE, 或者 POP中的一个
key 唯一ID
常用的三种history
// HTML5 history, 推荐
import createHistory from 'history/lib/createBrowserHistory'
// Hash history
import createHistory from 'history/lib/createHashHistory'
// 内存 history (如:node环境)
import createHistory from 'history/lib/createMemoryHistory'
hashHistory
不需要服务器配置,在URL生成一个哈希来跟踪状态,通常在测试环境使用,也可以作为发布环境使用。
import { Provider } from 'react-redux'
import { Router, hashHistory} from 'react-router'
ReactDOM.render((
<Provider store={store}>
<Router history={hashHistory}>
<Route>
//你的route
</Route>
</Router>
</Provider>),
document.getElementById('root')
);
browserHistory
需要服务器端做配置,路径是真实的URL,是官方推荐首选。
客户端配置
import { Provider } from 'react-redux'
import { Router, browserHistory } from 'react-router'
ReactDOM.render((
<Provider store={store}>
<Router history={browserHistory}>
<Route>
//你的route
</Route>
</Router>
</Provider>),
document.getElementById('root')
);
服务端配置
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// 通常用于加载静态资源
app.use(express.static(__dirname + '/public'))
// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)
为什么browserHistory需要服务端配置
因为真实URL其实是指向服务器资源,比如我们经常使用的API接口,也是一个真实URL的资源路径,当通过真实URL访问网站的时候,第一次访问的是网站的域名,这个时候可以正常加载我们的网站js等文件,而用户手动刷新网页时,由于路径是指向服务器的真实路径,服务器端没有做路由配置,就会导致资源不存在,用户访问的资源不存在,返回给用户的是404错误。
通过hashHistory来生成的URL就不会出现这样的问题,因为他不是指向真实的路由。