React Router v4 replace history when component is unmounted

风流意气都作罢 提交于 2021-02-04 06:29:12

问题


I have a app which has the Following Components

|__Base - /home/Base

|__Try - /home/Base/:try

|__Report - /home/Base/:try/report

Base is the Starting screen where the user hits a button and clicks on Try and after trying some things he hits submits which generates reports which has some back end interactions and when the data is fetched it loads the Reports.

So what i want is when the user hits the back button from the Reports Page he should not land on the Try page but on the Base page .

For that to work i went through the react router documentation and was trying to use history.replace on componentWillUnmount for Reports Page

this.props.history.replace(`/home/Base`, {
  pathname: `/home/Base`,
  search: null,
  state: {
    isActive: true
  }
}, null);

In case the Report Page is FullyLoaded and i press the back button it works but calls the Try Render Method too and then takes me to the Base Page , But in case of Reports Not fully Loaded and i press the back button while the loading spinner is in progress it goes to base page still but also mounts and unmounts the TRY component.

What am i missing here , what causes it to mount/unmount or render the previous component and then load the base component even though i replace the history stack ?


回答1:


Reason

Related with this issue

React v16, changing routes, componentWillMount of the new route is called before componentWillUnmount of the old route

Update:

Solution (checked, update online demo later)

Use react-router-last-location to get previous pathname

import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom';
import { LastLocationProvider } from 'react-router-last-location';

<BrowserRouter>
  <LastLocationProvider>
    <Switch>
     ...
    </Switch>
  </LastLocationProvider>
</BrowserRouter>

Check previous pathname in componentWillMount, if it's from certain page, push a new pathname to route.

  componentWillMount() {
    const { history, lastLocation } = this.props;
    if (lastLocation?.pathname === '/home/Base/:try/report') {
      history.push({pathname: '/home/Base'});
    }
  }

You can use the HOC they provide or write it yourself refer to the lib's source to reduce the dependencies

import { withLastLocation } from 'react-router-last-location';

interface Props {
  lastLocation: any,
  history: any,
}

export const YourComponent = withLastLocation(connect(
  ...
))

In this way you can redirect all the routing process from certain pages without mount current page, no matter you clicked a back button or clicked the back in your browser.



来源:https://stackoverflow.com/questions/60053624/react-router-v4-replace-history-when-component-is-unmounted

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