简体   繁体   中英

React-router-dom calls constructor first before unmounting the component

I want my component to re-render every time when I click on the link in the header. So I used the component props in route to rerender my component.

<Route
 exact
 path="/assets"
 component={props => (<AssetsView {...props} />)}
/>

In the docs it is stated that

This results in the existing component unmounting and the new component mounting instead of just updating the existing component.

But, when I click the Link, the constructor is called first, followed by componentWillMount and componentWillUnmount is the last lifecycle to be called.

I have 2 components Edit and Table view and I navigate between these two components using react-router-dom. When I am in Edit component I want to change the redux state on unmount based on the condition before the Table component mounts and use the changed redux state in the initial state (using Constructor) of Table component. How can this be achieved?

sample program - https://codesandbox.io/s/kmy387l59o

Did anyone face this problem?

From React16 onwards componentWillUnmount is asynchronous that's why it is called after next components componentWillMount. For more details check out the discussion here.

In React 15, ComponentWillUnmount called first before the rendering of next component in DOM. In the current version (v16), ComponentWillUnmount was called after the mounting of next component.

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