Heim  >  Fragen und Antworten  >  Hauptteil

Wie kann ich den Benutzer auf eine andere Seite umleiten, wenn der Benutzer die Seite neu lädt?

In React versuche ich, onunload und onbeforeunload zu verwenden, um den Benutzer nach dem Neuladen von der aktuellen Seite auf eine andere Seite umzuleiten. Aber nach dem ersten Neuladen zeigt es an, dass sich die URL geändert hat und kehrt wieder zur aktuellen Seite zurück. Nach dem zweiten Neuladen gelangt man zur Weiterleitungsseite. Das sind einige Codes, die ich ausprobiert habe...

Test 001: Nach dem Bestätigen/Anklicken der Schaltfläche „Seite verlassen“ sollte eine Weiterleitung erfolgen. Tatsächlich wird diese Seite aufgerufen und zur vorherigen Seite weitergeleitet. >_<<

import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

const MyComponent = () => {
  const history = useHistory();

  useEffect(() => {
    const handleBeforeUnload = (event) => {
      // Prevent the default dialog box from showing
      event.preventDefault();
      // Redirect the user to the desired page
      history.push('/redirected-page');
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [history]);

  // Rest of your component code...

  return (
    // JSX for your component...
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>

Test 002: Dann dachte ich, es könnte ein Zeitproblem sein und habe einen Timer eingestellt. Jetzt wird es noch schlimmer! Da wird es nicht hingehen.

useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();

      // Delay the redirection by 100 milliseconds
      setTimeout(() => {
        history.push('/Applicant-profile');
      }, 100);
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [history]);

P粉036800074P粉036800074263 Tage vor350

Antworte allen(2)Ich werde antworten

  • P粉926174288

    P粉9261742882024-01-30 00:55:59

    试试这个:

    import React, { useState, useEffect } from 'react';
    import { Redirect } from 'react-router-dom';
    
    const MyComponent = () => {
     const [shouldRedirect, setShouldRedirect] = useState(false);
    
      useEffect(() => {
       const handleBeforeUnload = (event) => {
        // Custom logic to determine if the page is being reloaded
        // You can check for specific conditions or simply set the flag to true 
       unconditionally
      const isReloading = true;
    
      if (isReloading) {
        event.preventDefault();
        setShouldRedirect(true);
       }
     };
    
     window.addEventListener('beforeunload', handleBeforeUnload);
    
     return () => {
       window.removeEventListener('beforeunload', handleBeforeUnload);
     };
    }, []);
    
    if (shouldRedirect) {
     // Replace 'path/to/redirect' with the actual path you want to redirect to
     return ;
    }
    
     // Render your component content here
     return 
    Hello, World!
    ; };

    导出默认的MyComponent;

    Antwort
    0
  • P粉938936304

    P粉9389363042024-01-30 00:49:02

    浏览器“弹跳效应”或“双重重新加载”问题,即页面在尝试使用 beforeunload 事件重定向用户后重新加载两次,由于浏览器安全措施的原因,可能很难完全阻止。但是,您可以采用某些技术来最大程度地减少其影响。 一种有效的方法是将标志数据存储到全局某个位置,您可以在其中跟踪该用户重新加载该页面。

    这个人以某种方式解决了这个问题

    我有另一个解决方案,即在 localstorage / sessionStorage 中存储一个标志,然后在重定向成功时销毁它。下面是代码,您可以按照自己的方式使用它。

    const current_url = window.location.pathname;
    
    // this function will work only when you do reload. 
      window.onbeforeunload = function () {
        localStorage.setItem("page",current_url) // Store the page URL 
      };
    
    // After first redirection and due to bounce effect will come back to current page.
      useEffect(() => {
      
      // if your localstorage have the key "page and the value is the current page...
        if(localStorage.getItem("page") === current_url){
          
          localStorage.removeItem("page"); // also you have to remove the item from localstorage. 
          history.push("/where_you_want_to redirect") // ... then it will redirect you to somewhere you wish.
        }
      },[])

    Antwort
    0
  • StornierenAntwort