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;
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

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:
So after the render() is executed, the componentDidMount is getting executed and there's no change after any state change.

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With