React: componentDidUpdate the same for two different component instances?

I am writing a React application (ES6, v16) (typescript) with a v4 reaction router. I observe very strange behavior. Here is my rendering code (very simplified):

render() { <Switch> <Route path="/foo/add" render={ props => { return ( <FormEntry title="add new" /> ); }} /> <Route path="/foo/edit/:id" render={ props => { return ( <FormEntry title="edit item" /> ); }} /> </Switch> } 

And here is the FormEntry component (simplified):

 class FormEntry extends React.Component< { title: string }, any > { render() { return ( <div> {this.props.title} </div> ); } componentDidMount() { // code goes here } componentDidUpdate() { // code goes here } } 

Now, when I click the "/ foo / add" link inside the application, the handler in the first component "Route" starts (as expected) and the component "FormEntry" is mounted. The componentDidMount method is rightfully launched.

Now I click the link "foo / edit / 1". The second route handler starts.

This time, the componentDidMount lifecycle method does not start inside the FormEntry component; the componentDidUpdate method is called. But this is cleaner than the other "instance" of FormEntry that mounts. I expected to see how life cycle methods started ...

It looks like there is only one instance of "FormEntry" in my application. So why in the second case (when the Route handler for the url is "foo / edit: id") this instance does not go through all the life cycle methods?

Is this a change in version v16? (I did not observe this behavior in previous versions of the reaction).

Your understanding will be greatly appreciated.

+5
source share
1 answer

<Switch> check the JSX previous agreed route and compare it with the new JSX next route.

If it matches, it will use it and update the changed values ​​without reinstalling the components.

Otherwise, he will create new response elements and create new components.

Check here: https://github.com/ReactTraining/react-router/pull/4592

To do this, use the following attributes:

 render() { <Switch> <Route path="/foo/add" render={ props => { return ( <FormEntry key="1" title="add new" /> ); }} /> <Route path="/foo/edit/:id" render={ props => { return ( <FormEntry key="2" title="edit item" /> ); }} /> </Switch> } 
+2
source

Source: https://habr.com/ru/post/1274718/


All Articles