I currently set up a simple React JS application with 2 pages - A landing page and a 'Room' page. I am using the useHistory hook from react-router.
Expected behavior
When user clicks refresh in the 'Room' page, the application shall go back to the 'Landing' page.
Projected behavior
User hits refresh, pathname did change to the pathname of the Landing page for a split second. And the 'Room' page mounted itself again, replacing the 'Landing' page.
Here are the code snippets of my application:
App.js
import LandingPage from './components/pages/LandingPage'; import RoomPage from './components/pages/RoomPage'; function App() { return ( <Router> <Switch> <Route exact path="/" component={LandingPage}/> <Route path="/room-:roomId" component={RoomPage}/> </Switch> </Router> ); } export default App;
Landing Page
function LandingPage(){ const history = useHistory(); function toRoomPage(){ history.push('/room-{room_id here}'); } function onAnotherBtnClick(){ console.log("hi"); } return ( <div className="landing-page-container page-container"> <div className="landing-page-inner-panel"> <div className="landing-page-inner-top"> Landing Page </div> <div className="landing-page-button-wrapper"> <button className="btn btn-primary" onClick={toRoomPage}>To Room Page</button> </div> <div>or</div> <div className="landing-page-button-wrapper"> <button className="btn btn-secondary" onClick={onAnotherBtnClick}>Another Button</button> </div> </div> </div> ); } export default LandingPage;
Room Page
function RoomPage(){ const history = useHistory(); function onUnload(){ history.replace("/"); } useEffect(() => { window.addEventListener("unload", onUnload) return () => { window.removeEventListener("unload", onUnload); } }, []) return ( <div className="room-page-container page-container"> Room Page </div> ); } export default RoomPage;
I'm not too sure how the DOM behaves on refresh, as I am fairly new to React JS. I've tried both .replace()
and .push()
, but it still doesn't work.
I've been searching through the web for 2 hours straight, yet to no avail. Hopefully someone could give me some light. Thanks a lot in advance.
https://stackoverflow.com/questions/67014922/react-js-how-do-i-redirect-back-to-my-main-page-when-user-refreshes-another-par April 09, 2021 at 12:03PM
没有评论:
发表评论