寫在前面
此係列來源於開源項目:前端 100 問:能搞懂 80%的請把簡歷給我
爲了備戰 2021 春招
每天一題,督促自己
從多方面多角度總結答案,豐富知識
react-router 裏的 <Link> 標籤和 <a> 標籤有什麼區別
簡書整合地址:前端 100 問
正文回答
// 先看Link點擊事件handleClick部分源碼
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 件事情:
- 有 onclick 那就執行 onclick
- click 的時候阻止 a 標籤默認事件(這樣子點擊<a href="/abc">123</a>就不會跳轉和刷新頁面)
- 再取得跳轉 href(即是 to),用 history(前端路由兩種方式之一,history & hash)跳轉,此時只是鏈接變了,並沒有刷新頁面
一個 bug 記錄
之前遇到過一個 bug, 在一個 SPA 裏點擊一個鏈接按鈕後,redux 裏的數據都丟了。後來才發現,不知道誰寫了一個 a,沒有用 Link。相當於重新打開了一個 SPA。