React - componentDidMount() lifecycle method

0 votes
522 views
added Nov 11, 2019 in React by LC Marshal Captain (25,790 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, 2019 by LC Marshal Captain (25,790 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, 2019 by LC Marshal Captain (25,790 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, 2019 by lcjr First Warrant Officer (11,990 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.
...