Separate Container Components From Presentational Components: Apply


#1

I dont understand how the following code is getting called and how it works ! ?
What is interval doing here and what do these below methods do ?
how are they invoked here in this code ?



componentDidMount() {
    this.interval = setInterval(this.nextGP, 5000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }



#2

Lifecycle methods are methods that get called at certain moments in a component’s life.

There are three categories of lifecycle methods: mounting, updating, and unmounting

There are three mounting lifecycle methods

componentWillMount
render
componentDidMount

When a component mounts:

ReactDOM.render(
  <element />,
  document.getElementById('root')
);

it automatically calls these three methods, in order

ReactJS is handling this methods call when you mount a component, you can use this to your advantage when designing your app.

Impossible to say what exactly interval is without knowing where the example is coming from

componentDidMount is called when a component is rendered for the first time, so this is a good place to start an interval (to start an update cycle to update the element every 5 seconds)

then when the component is removed, componentWillUnmount is called, you clear the interval


#3

The code comes from this example. :

import React from ‘react’;
import ReactDOM from ‘react-dom’;
import {GuineaPigs} from ‘…/components/GuineaPigs’;

const GUINEAPATHS = [
https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-1.jpg’,
https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-2.jpg’,
];

class GuineaPigsContainer extends React.Component {
constructor(props) {
super(props);

this.state = { currentGP: 0 };

this.interval = null;

this.nextGP = this.nextGP.bind(this);

}

nextGP() {
let current = this.state.currentGP;
let next = ++current % GUINEAPATHS.length;
this.setState({ currentGP: next });
}

componentDidMount() {
this.interval = setInterval(this.nextGP, 5000);
}

componentWillUnmount() {
clearInterval(this.interval);
}

render() {
let src = GUINEAPATHS[this.state.currentGP];
return ;
}
}

ReactDOM.render(
<GuineaPigsContainer />,
document.getElementById(‘app’)
);


#4

do you still have questions left after my explanation? The interval in this case, is to display a new picture every 5 seconds


#5

Thank you for the detailed explanation of components lifecycle methods.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.