Are you first timer at lazacode.org? Why not join us and start exchange your programming knowledge with everyone. Register today!

React - componentDidMount() lifecycle method

0 votes
20 views
added Nov 11 in React by LC Marshal Captain (25,420 points)

The componentDidMount() method runs after the component output has been rendered to the DOM. [src]

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.[src]

3 Responses

0 votes
responded Nov 11 by LC Marshal Captain (25,420 points)
componentDidMount() {
	if (Cookies.get('accesskey') !== undefined) {
		this.setState({
			hideLogin: true,
		});
	}
	const defenderPg = Cookies.getJSON('defenderPage');
	if (defenderPg !== undefined) {
		if (defenderPg.agenturl !== undefined) {
			this.isDriver = true;
			this.driverUrl = defenderPg.driverUrl;
		} else {
			this.isDriver = false;
		}
	} else {
		this.isDriver = false;
	}
}

 

0 votes
responded Nov 11 by LC Marshal Captain (25,420 points)
//sample
import React, { Component } from 'react';

class Defender extends Component {

  constructor(props){
    super(props);
    this.state = {
      data: 'Gray wolf'
    }
  }
  componentWillMount(){
    console.log('First this called');
  }

  getData(){
    setTimeout(() => {
      console.log('Our data is fetched');
      this.setState({
        data: 'Hi Solihull'
      })
    }, 1000)
  }

  componentDidMount(){
    this.getData();
  }

  render() {
    return(
      <div>
      {this.state.data}
    </div>
    )
  }
}

export default Defender;

 

0 votes
responded Nov 15 by lcjr Sergeant (1,540 points)
componentDidMount() {
    const userDetail = Cookies.getJSON('userDetail');
    if (userDetail !== undefined) {
      this.setState({
        isLoggedin: true,
        userData: userDetail,
        accessKey: Cookies.get('accesskey'),
      });
    } else {
      Router.push({
        pathname: '/',
      });
    }
  }

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...