[英]Go back react router, and detect if the history have no items to hide the button
I want to make a button for going back, I did the following:我想制作一个返回按钮,我做了以下操作:
const GoBackBtn = ()=>{
const navigate = useNavigate()
return (<button onClick={()=>navigate(-1)}> {'<='} </button>)
}
It works great, however, the problem is when I first visit the webpage where this component is placed on and I'm in the root:它工作得很好,但是,问题是当我第一次访问这个组件所在的网页并且我在根目录中时:
http://localhost:3000/ http://localhost:3000/
the problem which happens is when you click on the button, it takes you out of the website to the blank page (the browser home page, if you're using chrome, the home page of chrome).发生的问题是,当您单击按钮时,它会将您从网站带到空白页面(浏览器主页,如果您使用的是 chrome,则为 chrome 的主页)。
I want to prevent that by hiding the button if there were no items in the history of the router.如果路由器的历史记录中没有项目,我想通过隐藏按钮来防止这种情况发生。
But how I can detect that?但是我怎么能检测到呢?
I want to keep this functionality only on my website, I don't want it to navigate outside my website or to others websites我只想在我的网站上保留此功能,我不希望它在我的网站之外或其他网站上导航
React Router has a hook called useLocation
. React Router 有一个叫做
useLocation
的钩子。 Using this hook, you can get the path of the current route.使用这个钩子,你可以得到当前路由的路径。 The path for the root route is
/
.根路由的路径是
/
。
I would add the condition such as:我会添加条件,例如:
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.