How the code works?


#1


Currently I am stuck here. I do not know how the code works since as I know, if ReactDOM.render() works, it will only render the guineapigs and only the render part of guineapigs will be executed. At the render of guinea pigs, there is only src which is GUINEAPATHS[this.state.currentGP]. It did not call any function at all (nextGP(), componentDidMount(), componentWillUnmount()). SO how these function executed while it is not in the rendered side.

Thanks!


https://www.codecademy.com/en/courses/react-102/lessons/container-presentational-components/exercises/container-presentational-components-intro


import React from 'react';
import ReactDOM from 'react-dom';

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',
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-3.jpg',
  'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-4.jpg'
];

export class GuineaPigs 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 (
      <div>
        <h1>Cute Guinea Pigs</h1>
        <img src={src} />
      </div>
    );
  }
}

ReactDOM.render(
  <GuineaPigs />, 
  document.getElementById('app')
);


#2

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