Why is not getInitialState called for my React class?

I am using ES6 classes with Babel. I have a React component that looks like this:

import { Component } from 'react'; export default class MyReactComponent extends Component { getInitialState() { return { foo: true, bar: 'no' }; } render() { return ( <div className="theFoo"> <span>{this.state.bar}</span> </div> ); } } 

It does not seem to getInitialState called because I get this error: Cannot read property 'bar' of null .

+30
javascript reactjs
Jul 29 '15 at 19:17
source share
3 answers

Developers talk about ES6 class support in Release Notes for v0.13.0 . If you are using an ES6 class that extends React.Component , you should use constructor() instead of getInitialState :

An API is basically what you expect, with the exception of getInitialState. We thought that the idiomatic way to determine the state of a class is to simply use a simple instance property. Like getDefaultProps and propTypes, these are really just constructor properties.

+56
Jul 29 '15 at 19:17
source share

Code to accompany Natans answer:

 import { Component } from 'react'; export default class MyReactComponent extends Component { constructor(props) { super(props); this.state = { foo: true, bar: 'no' }; } render() { return ( <div className="theFoo"> <span>{this.state.bar}</span> </div> ); } } 
+27
Nov 06 '15 at 13:27
source share

To expand a little what it means

getDefaultProps and propTypes are really just constructor properties.

the "on the constructor" bit is a weird wording. In the usual OOP language, this means that they are "static class variables"

 class MyClass extends React.Component { static defaultProps = { yada: "yada" } ... } 

or

 MyClass.defaultProps = { yada: "yada" } 

you can also refer to them in the class, for example:

 constructor(props) { this.state = MyClass.defaultProps; } 

or with something declared as a static class variable. I don’t know why this is not mentioned anywhere on the Internet regarding ES6 classes :?

see documents .

+1
Jun 08 '16 at 7:45
source share



All Articles