
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.3.4 history.createHref
createHref方法可将location对象转换为对应的URL字符串,在React Router源码中使用到了该方法,如在7.1.2节中,Link组件内部使用createHref方法创建a标签的href属性值。由于该方法为history对象的一个属性,所以开发者也可通过history.createHref使用该方法。
在使用hashHistory.createHref方法时,注意createHref不会对原字符串做任何编解码处理:

并且hashHistory的createHref会判断HTML文档流中是否有href属性的base元素,其源码实现如下:


在文档流中没有base元素的情况下,调用history.createHref创建路径,得到的字符串将以“#”开头:

如果文档流中有base元素且href有值(任何值均可),假设当前路径为/foo/baz,则调用history.createHref会得到:

此种情况将会得到包括浏览器pathname的完全的href路径。
由于在有base元素的情况下需要使用完全的路径设置到a标签的href属性上,才能使得浏览器识别出该a标签是否被访问过,因此,createHref源码才需要判断文档流中的base元素并拼接出全路径,以便正确设置a标签的属性值。