usePreviousRoute.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import {useLocation} from 'react-router-dom';
  2. import {useEffect, useRef, useState} from 'react';
  3. import {toast} from "react-toastify";
  4. import {ROUTE_PATH} from "@constants/routes";
  5. const usePreviousRoute = () => {
  6. const location = useLocation();
  7. const [preLocation, setPreLocation] = useState({});
  8. // const prevLocation = useRef(null);
  9. // const currentLocation = useRef(null);
  10. const [currentLocation, setCurrentLocation] = useState({});
  11. const [gameID, setGameID] = useState(0);
  12. const parseGameID = ()=>{
  13. let pathname=location.pathname;
  14. let gid=0;
  15. if (pathname.startsWith(ROUTE_PATH.GAME)){
  16. let path="";
  17. let temp=pathname.split("?");
  18. path=temp.shift();
  19. temp=path.split("/");
  20. path=temp.pop();
  21. gid=Number(path);
  22. }
  23. setGameID(gid);
  24. }
  25. useEffect(() => {
  26. setPreLocation({...currentLocation})
  27. setCurrentLocation({...location});
  28. parseGameID();
  29. }, [location.pathname]);
  30. return {
  31. preLocation,
  32. gameID
  33. };
  34. }
  35. export default usePreviousRoute