Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the variable declared in ComponentWillMount Undefined?

I have a component of this type. For simplicity, I have removed all unnecessary code.

This component displays a button when clicking on which the value of the variable I declared in ComponentWillMount should be displayed in the console, but when clicked, the console displays undefined, why?

    'use strict';
    class LoginFormComponent extends React.Component {

      handleSubmit() {
        console.log(this.model); //undefined
      }

      componentWillMount() {
        this.model = 123;
      }

      render() {
                    console.log(this.model);  //123
        var styles = this.props.styles;

        return (
                <CM.MUI.FlatButton
                style={styles.buttonStyle}
                onClick={this.handleSubmit}
                label={CM.gettext('Login')}/>
        );
      }
    };

    module.exports = LoginFormComponent;

1 Answers

You should be using componentDidMount for setting up the instance properties as the content in componentWillMount will not be in the instance scope as the component isn't mounted yet.

Also, use a => fat arrow function to get the access to this instance of your component.

Updated Code:

class LoginFormComponent extends React.Component {
  handleSubmit = () => {
    console.log(this.model); // 123
  }

  componentDidMount() {
    this.model = 123;
  }

  render() {
    console.log(this.model); //123
    var styles = this.props.styles;

    return (
      <CM.MUI.FlatButton
        style={styles.buttonStyle}
        onClick={this.handleSubmit}
        label={CM.gettext("Login")}
      />
    );
  }
}

export default LoginFormComponent;

Console

preview

Demo: agitated-solomon-3rrow - CodeSandbox

More information

As explained in this demo: summer-violet-g4pyd - CodeSandbox, it looks like the way React works is as follows:

  1. Constructor
  2. componentWillMount
  3. Render
  4. componentDidMount

So after the render() is executed, the componentDidMount is getting executed and there's no change after any state change.

preveiw

If you want something to be there, please put them in constructor().

Moreover, componentWillMount is deprecated and you should not use that in the next releases.

like image 171
Praveen Kumar Purushothaman Avatar answered Apr 26 '26 14:04

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!