简体   繁体   中英

Is there a way to force react-router-dom to redirect the page on a page refresh?

I am using react-router-dom on react app for a website build. I am wondering, is it possible to redirect the current page when a person chooses to refresh the page?

Here is my working code to prompt a user about refreshing a page (I found it on another stack overflow article):

 window.addEventListener("beforeunload", function (e) { let confirmationMessage = 'It looks like you have been editing something. ' + 'If you leave before saving, test will be lost.'; (e || window.event).returnValue = confirmationMessage; return confirmationMessage; });

I have the current site URL end in "/data-gathering", but unfortunitely it requires input from a prior page or it will break. If a user refreshes the page, it resets the website if their on that page. So I was wondering if we could get route it to "/index.html".

I have tried:

 //1st Attempt const reroute = ( <Route exact path="/data-gathering"> <Redirect to="/index.html" /> </Route> ) window.addEventListener("beforeunload", function (e) { let confirmationMessage = 'It looks like you have been editing something. ' + 'If you leave before saving, test will be lost.'; (e || window.event).returnValue = confirmationMessage; return reroute; }); //__________________________________________________________________ //2nd Attempt window.addEventListener("beforeunload", function (e) { let confirmationMessage = 'It looks like you have been editing something. ' + 'If you leave before saving, test will be los5t.'; (e || window.event).returnValue = confirmationMessage; return ( <Route exact path="/data-gathering"> <Redirect to="/index.html" /> </Route> ) });

But both failed. Any ideas on how to make this work?

The problem with this approach is that it will not work if users navigate to that route directly, eg because they bookmarked it or manually entered the route in the url bar.

I'd go with a different approach to fix this. The component that renders on /data-gathering should check, if the required values are available and if not redirect to the page that lets you enter the required data (or another sane default). Something like that:

const DataGathering = ({data}) => {
  if (!data) return <Redirect to="/enter-data" />

  // ... render whatever should be rendered if data is already there

}

Of course you can still show the warning if users try to navigate away or refresh the page to warn them about data loss. But you don't have to redirect them as your component will do that when it renders without the required data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM