score:1

that's expected because state needs to be defined before using. the common way with es6 classes is to define initial state from within constructor, a such:

class mycmp extends react.component {
    constructor() {
        super(); // don't forget to call superclass constructor
        this.state = {foo: 1};
    }

    componentdidmount() {
        console.log(this);//1
        console.log(this.state);//2
    }
}

if you use proposal-grade javascript (e.g. if you have stage-0 or some other stage number as a profile in your babel configuration), then you can define it as a class property too:

class mycmp extends react.component {
    state = {
        foo: 1
    };

    componentdidmount : function() {
        console.log(this);//1
        console.log(this.state);//2
    }
}

if you don't use es6 classes, you would do something like:

var mycmp = react.createclass({
    getinitialstate: function() {
        return {
            foo: 1
        }
    },
    componentdidmount : function() {
        console.log(this);//1
        console.log(this.state);//2
    }
}

i hope that helped. enjoy react!


Related Query

More Query from same tag