Out of curiosity, I just wanna know what will happen if I use setState() function in constructor of a Class in React Native or ReactJS?
Such as:
Error Message would be
Uncaught TypeError: Cannot read property 'VARIABLE_NAME' of null
Please see the following two jsfiddle snippets.
Case 1) Working solution jsfiddle
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'world'
}
}
render() {
return {this.state.name}
}
}
ReactDOM.render( , document.getElementById('container'));
Case 2) Not working solution
class Hello extends React.Component {
constructor(props) {
super(props);
this.setState({
name: 'hello'
});
}
render() {
return {this.state.name}
}
}
ReactDOM.render( , document.getElementById('container'));
Conclusion:
My rule of thumb, inside constructor uses this.state = {} directly, other places use this.setState({ });