首页 > 解决方案 > 单击刷新然后返回按钮时如何登陆到现有页面

问题描述

我遇到了一个功能问题,其中我编写了一个代码,该代码阻止用户在单击后退按钮时转到上一页。对于相同的代码,当我刷新页面然后单击后退按钮时,它会返回上一页。我不希望这种体验,并且希望用户保持在同一页面中,即使用户刷新并单击后退按钮也是如此。

我编写的现有代码如下。我可以在其中加入一些东西还是需要编写一个新组件?

import React, { useEffect } from 'react'

const popupHandler = () => window.history.pushState(null, document.title, window.location.href)

const usePreventBackButton = () => {
   useEffect(() => {
     window.history.pushState(null, document.title, window.location.href);
     window.addEventListener('popstate', popupHandler)
     return () => window.removeEventListener('popstate', popupHandler)
   }, [])
}

export default usePreventBackButton

标签: javascriptreactjs

解决方案


推荐阅读