DeanPaul / blog

MIT License
2 stars 1 forks source link

React Router #15

Open DeanPaul opened 6 years ago

DeanPaul commented 6 years ago

synchronize URL and UI interface. Base on history.js(a 3rd part lib)

capture

DeanPaul commented 6 years ago

History

history是一个独立的第三方js库,可以用来兼容在不同浏览器、不同环境下对历史记录的管理,拥有统一的API。具体来说里面的history分为三类:

老浏览器的history: 主要通过hash来实现,对应createHashHistory 高版本浏览器: 通过html5里面的history,对应createBrowserHistory node环境下: 主要存储在memeory里面,对应createMemoryHistory 上面针对不同的环境提供了三个API,但是三个API有一些共性的操作,将其抽象了一个公共的文件createHistory:

// 内部的抽象实现
function createHistory(options={}) {
  ...
  return {
    listenBefore, // 内部的hook机制,可以在location发生变化前执行某些行为,AOP的实现
    listen, // location发生改变时触发回调
    transitionTo, // 执行location的改变
    push, // 改变location
    replace,
    go,
    goBack,
    goForward,
    createKey, // 创建location的key,用于唯一标示该location,是随机生成的
    createPath,
    createHref,
    createLocation, // 创建location
  }
}

上述这些方式是history内部最基础的方法,createHashHistory、createBrowserHistory、createMemoryHistory只是覆盖其中的某些方法而已。其中需要注意的是,此时的location跟浏览器原生的location是不相同的,最大的区别就在于里面多了key字段,history内部通过key来进行location的操作。

function createLocation() {
  return {
    pathname, // url的基本路径
    search, // 查询字段
    hash, // url中的hash值
    state, // url对应的state字段
    action, // 分为 push、replace、pop三种
    key // 生成方法为: Math.random().toString(36).substr(2, length)
  }
}
DeanPaul commented 6 years ago

其中在react-router中,URL对应Location对象,而UI是由react components来决定的,这样就转变成location与components之间的同步问题

DeanPaul commented 6 years ago

在react-router中最主要的component是Router RouterContext Link,history库起到了中间桥梁的作用。 upper

internal