随手写系列--从react-router的Link标签与a标签差异对比的反思hash与history路由形式区别原理

446 阅读1分钟

直接说Link行为:

  if (_this.props.onClick) _this.props.onClick(event);

      if (!event.defaultPrevented && // onClick prevented default
      event.button === 0 && // ignore everything but left clicks
      !_this.props.target && // let browser handle "target=_blank" etc.
      !isModifiedEvent(event) // ignore clicks with modifier keys
      ) {
          event.preventDefault();

          var history = _this.context.router.history;
          var _this$props = _this.props,
              replace = _this$props.replace,
              to = _this$props.to;


          if (replace) {
            history.replace(to);
          } else {
            history.push(to);
          }
        }

Link做了3件事情:

  1. 有onclick那就执行onclick
  2. click的时候阻止a标签默认事件
  3. 再取得跳转href(即是to),用history(前端路由两种方式之一,history & hash)跳转,此时只是链接变了,并没有刷新页面

目前hash和history路由形式都是url变化,再通过使用各自的监听路由变化的方法去匹配路由组件进行挂载

hash的hashChange

history的onpopstate--还有replcaeState/pushState来管控历史路由数据