Listen to back button in mobile browser and e.preventDefault() then use our separate function in react function

牧云@^-^@ 提交于 2021-01-07 01:37:27

问题


I am working on a react web app add want to preventDefault back button to my function in react function

for exact code use check -https://github.com/rishabhjainfinal/react-expence-calculator/blob/main/src/App.js

yes I can use react routing but I wanna test this way first

function App() {
    
     function onBack(){
        if (CP === "Month"){
            UpdateCP("Year")
        }
        else if (CP === "Day"){
            UpdateCP("Month")
        }        
    }    
    
    //some event listener function to prevent to go back 

    switch (CP){
        case 'Day':
            return (<Day date={AD} CP={CP} UpdateCP={UpdateCP}/>)
        case 'Year':
            return (<Year monthNames={monthNames} CP={CP} UpdateCP={UpdateCP} UpdateAM={UpdateAM} Save_in_excel={Save_in_excel}/>)
        default :
            return (<Month month={AM} CP={CP} UpdateCP={UpdateCP} UpdateAD={UpdateAD} AM={AM} AY={AY} monthNames={monthNames} />)
    }
}

This is my first react app and want to do it this way only.

Yes, there are many different ways but none of then is working:

  • Intercept/handle browser's back button in React-router?
  • How to capture back button of the browser without using pushstate?
  • How can I stop the browser back button using JavaScript?

the more detailed description -> supposed you created a react P.W.App of single-page but you wanna change the components every time back button is pressed like mobile back button or browser back button, and this is only possible by listening to the press of the back-button and prevent default case and run my own function this takes 2 steps:-

  1. listen to the event
  2. run function

try using

const [finishStatus, setfinishStatus] = useState(false);

    useEffect(() => {
        const onBackButtonEvent = (e) => {
            console.log('kdfjlsdjfds')
            e.preventDefault();
            if (!finishStatus) {
                if (window.confirm("Do you want to go back ?")) {
                    setfinishStatus(true)
                    // your logic
                    // props.history.push("/");
                } else {
                    window.history.pushState(null, null, window.location.pathname);
                    setfinishStatus(false)
                }
            }
        }
    
        window.history.pushState(null, null, window.location.pathname);
        window.addEventListener('popstate', onBackButtonEvent);
        return () => {
            window.removeEventListener('popstate', onBackButtonEvent);  
        };
    });

this code does nothing in my app (no effect at all) for of componentDidMount and componentDidUnMount in useEffect hook, our whole page is a single component when it Unmounts page unloads 😥


回答1:


I still don't see where you try to prevent any back navigation, but you can use history.block from the router context. When a "POP" action is initiated you can run your custom logic to allow or block the route transition from occurring.

The following is an example usage:

const history = useHistory();

useEffect(() => {
  const unblock = history.block((location, action) => {
    if (action === "POP") {
      // Return true to allow transition, false to block
      return window.confirm("Navigate Back?");
    }
  });

  return () => {
    unblock();
  };
}, []);

Full example code:

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

  React.useEffect(() => {
    const unblock = history.block((location, action) => {
      if (action === "POP") {
        return window.confirm("Navigate Back?");
      }
    });

    return () => {
      unblock();
    };
  }, []);

  return (
    <div>
      <h3>Test Page</h3>
      <div>
        <p>Try navigating away</p>
      </div>
    </div>
  );
};

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Router>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/test">Test</Link>
          </li>
          <li>
            <Link to="/other">Other</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/test">
            <TestComponent />
          </Route>
          <Route path="/other">
            <div>
              <h3>Some Other Page</h3>
              <div>
                <p>This is some other page</p>
              </div>
            </div>
          </Route>
          <Route>
            <div>
              <h3>Home Page</h3>
              <div>
                <p>This is the home page</p>
              </div>
            </div>
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

Using window.beforeunload

Here is a fairly trivial example for how to use window.beforeunload.

React.useEffect(() => {
  const callback = (e) => {
    if (blockingCondition) {
      e.preventDefault();
      e.returnValue = "";
    }
  };

  window.addEventListener("beforeunload", callback);

  return () => window.removeEventListener("beforeunload", callback);
}, [blockingCondition]);



来源:https://stackoverflow.com/questions/65500562/listen-to-back-button-in-mobile-browser-and-e-preventdefault-then-use-our-sepa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!