react-router

监听路由改变

  1. react-router 用到了 history 库,browserHistory 监听 popstate 事件,hashHistory 监听 hashchange 事件

  2. 路由改变生成一个新的 location 对象,调用所有订阅的函数,传入新的 location

在路由改变时通知 Route

  • 在 Router 构造函数中调用 hisory.listen 进行订阅,this.setState({ location })来改变 location

  • Router 组件是一个 Context.Provider,location 是 context 的 value 属性之一。Route 组件是 Consumer 将接收到的最新的 location 等作为 props 传递给了子组件,子组件更新。

获取 history

  • 我们应该使用 Router 组件使用的 history 实例,而不是 createBrowserHistory 创建一个新的实例。(因为新的实例,basename 等属性可能不同)

  • react 内,useHistory

  • react 外,如下

// file history.js
import { createBrowserHistory } from 'history'
const history = createBrowserHistory(options)
export default history

// file b.jsx
import { Router } from 'react-router-dom'
import history from './history.js'
return <Router history={history}>{/* routes as usuall */}</Router>

// file c.js
import history from './history.js'

最后更新于