R
R
Rapen2017-04-08 13:30:46
JavaScript
Rapen, 2017-04-08 13:30:46

How are custom methods called in React components?

There is the following code, there is a component in which there are two methods componentDidMount, componentWillUnmount, one cyclically updates the state, the other stops updating how they work if they are not explicitly called. Code - creates the time, and constantly updates the state of the time.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

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

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Feninets, 2017-04-08
@fnnzzz

tick is called every second, and in its body there is setState, which, after it has finished, automatically calls the render () method. So every second your component is rerendered

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question