圖片來源: freeCodeCamp
Router 的 Push & Replace 的差別
在開發網頁的時候常常會在頁面之間切來切去,點錯了就切回上一頁,或是對上一頁的按鈕右鍵,可以看到目前的瀏覽器(或頁面)的足跡。
使用 Router(React or Vue)都會看到 Push & Replace 兩種方法來讓網頁切換到下一個畫面,那這兩個方法有什麼差別呢?
範例跟說明
Push
(通常是預設的方法):會將剛剛離開的網頁放入瀏覽紀錄,上一頁就能回去了。Replace
:離開的網頁不會保留,直接取代,上一頁不會回去剛剛的畫面。
Example Sandbox:
使用 React & React-router-dom
可以依序點選 PageC > PageB > PageA
切回上一頁時,由於 PageA Link
設定了 Replace
,會從 PageA
跳到 PageC
About Stack
Stack 的概念如上圖
我們第一個打開的頁面會最先存放,也就是在最下面
而每當我們透過 Push 進入到新網頁時,就會將記錄存入
若透過 Replace 則會覆蓋當前的(如上圖右)
按往前或往後瀏覽時就會發現,以上圖為例,PageB 消失了
相關官方資訊
replace: bool When true, clicking the link will replace the current entry in the history stack instead >of adding a new one. (react-router)
It acts like router.push, the only difference is that it navigates without pushing a new history entry, as its name suggests - it replaces the current entry. (vue router)