简体   繁体   English

Go 回反应路由器,并检测历史是否没有项目隐藏按钮

[英]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?但是我怎么能检测到呢?

  • React router v6反应路由器 v6
  • React v18反应 v18

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.

相关问题 react-router-dom: go 在 go 返回事件的历史上两次返回 - react-router-dom: go back twice in history on go back event 如何在 react-router-dom 中清除浏览器后退按钮历史记录 - How to clear browser back button history in react-router-dom 浏览器后退按钮忽略反应路由器历史推送 - React router history push is ignored by browser back button 使用路由器 go 后退按钮更改 state 反应导航 - React navigation with router go back button change state react-router 返回一个页面 你如何配置历史记录? - react-router go back a page how do you configure history? 单击按钮时页面返回历史记录 - Page go back in history when button clicked Angular 2 如何使用路由器和 location.go() 检测后退按钮按下? - Angular 2 How to detect back button press using router and location.go()? 在 SPA 中使用 React Router 来处理历史记录,包括浏览器后退按钮按下? - Using React Router in a SPA to handle history, including browser back button press? React-Router-后退按钮 - React-Router - Back Button 使用 react-router 的历史记录,有没有办法在不使用 push() 或 replace() 的情况下返回到特定的先前呈现的页面? - Using react-router's history, is there a way to go back to a specific previously rendered page without using push() or replace()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM