Intercept/handle browser's back button in React-router?

前端 未结 12 1064
滥情空心
滥情空心 2020-11-27 03:47

I\'m using Material-ui\'s Tabs, which are controlled and I\'m using them for (React-router) Links like this:

    

        
12条回答
  •  清酒与你
    2020-11-27 04:18

    For giving warning on the press of browser back in react functional components. do the following steps

    1. declare isBackButtonClicked and initialize it as false and maintain the state using setBackbuttonPress function.
    const [isBackButtonClicked, setBackbuttonPress] = useState(false);
    
    1. In componentdidmount, add the following lines of code
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', onBackButtonEvent);
    
    1. define onBackButtonEvent Function and write logic as per your requirement.

        const onBackButtonEvent = (e) => {
        e.preventDefault();
        if (!isBackButtonClicked) {
      
        if (window.confirm("Do you want to go to Test Listing")) {
          setBackbuttonPress(true)
          props.history.go(listingpage)
        } else {
          window.history.pushState(null, null, window.location.pathname);
          setBackbuttonPress(false)
        }
      }
      

      }

    2. In componentwillmount unsubscribe onBackButtonEvent Function

    Final code will look like this

    import React,{useEffect,useState} from 'react'
    
    function HandleBrowserBackButton() {
      const [isBackButtonClicked, setBackbuttonPress] = useState(false)
    
      useEffect(() => {
    
        window.history.pushState(null, null, window.location.pathname);
        window.addEventListener('popstate', onBackButtonEvent);
    
        //logic for showing popup warning on page refresh
        window.onbeforeunload = function () {
    
          return "Data will be lost if you leave the page, are you sure?";
        };
        return () => {
          window.removeEventListener('popstate', onBackButtonEvent);
        }
    
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, []);
      const onBackButtonEvent = (e) => {
        e.preventDefault();
        if (!isBackButtonClicked) {
    
          if (window.confirm("Do you want to go to Test Listing")) {
            setBackbuttonPress(true)
            props.history.go(listingpage)
          } else {
            window.history.pushState(null, null, window.location.pathname);
            setBackbuttonPress(false)
          }
        }
      }
    
      return (
        
    ) } export default HandleBrowserBackButton

提交回复
热议问题