routerUtils.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { stringify } from 'qs';
  2. import { useNavigate, useSearchParams } from 'react-router-dom';
  3. export const loginPath = '/login';
  4. export const toLoginPage = () => {
  5. const { search, pathname } = window.location;
  6. const urlParams = new URL(window.location.href).searchParams;
  7. const redirect = urlParams.get('redirect');
  8. if (window.location.pathname !== loginPath && !redirect) {
  9. window.location.href =
  10. loginPath +
  11. '?' +
  12. stringify({
  13. redirect: pathname + search,
  14. });
  15. }
  16. };
  17. export const useSmartRouter = () => {
  18. const navigate = useNavigate();
  19. const [searchParams] = useSearchParams();
  20. const smartNavigate = (path: string, params?: Record<string, any>) => {
  21. const currentParams = new URLSearchParams(searchParams);
  22. if (params) {
  23. Object.entries(params).forEach(([key, value]) => {
  24. currentParams.set(key, value);
  25. });
  26. }
  27. const queryString = currentParams.toString();
  28. navigate(`${path}${queryString ? `?${queryString}` : ''}`);
  29. };
  30. return smartNavigate;
  31. };