![](/img/trans.png)
[英]react-router-dom: go back twice in history on go back event
[英]Go back react router, and detect if the history have no items to hide the button
我想制作一個返回按鈕,我做了以下操作:
const GoBackBtn = ()=>{
const navigate = useNavigate()
return (<button onClick={()=>navigate(-1)}> {'<='} </button>)
}
它工作得很好,但是,問題是當我第一次訪問這個組件所在的網頁並且我在根目錄中時:
http://localhost:3000/
發生的問題是,當您單擊按鈕時,它會將您從網站帶到空白頁面(瀏覽器主頁,如果您使用的是 chrome,則為 chrome 的主頁)。
如果路由器的歷史記錄中沒有項目,我想通過隱藏按鈕來防止這種情況發生。
但是我怎么能檢測到呢?
我只想在我的網站上保留此功能,我不希望它在我的網站之外或其他網站上導航
React Router 有一個叫做useLocation
的鈎子。 使用這個鈎子,你可以得到當前路由的路徑。 根路由的路徑是/
。
我會添加條件,例如:
import { useLocation, useNavigate } from 'react-router-dom'
const goBackBtn = () => {
const location = useLocation()
const navigate = useNavigate()
const goBack = () => {
if (location.pathname !== '/') {
navigate(-1)
}
}
return (
<div>
{location.pathname !== '/' && (
<button onClick={goBack}>
{'<='}
</button>
)}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.