Responsive component life cycle

I am new to JavaScript. I recently started to learn ReactJS and read about the component life cycle. I realized that when the component was initialized, the loop looks like this:

GetDefaultProps -> GetInitialState -> ComponentWillMount -> Render -> ComponentDidMount

I also read what getDefaultProps()gets called before any instances are created. If I have the following code:

class Sample extends React.Component {
    constructor(props) {
        super(props);
        alert("In constructor");
    }
    getDefaultProps() {
        alert("In getDefaultProps");
    }
    render() {
        return <div></div>;
    }
}

React.render(<Sample/>, document.getElementById('app'));

I assumed that I would warn "In getDefaultProps", then "In constructor". But only "In the constructor" is warned. Why is this so?

+4
source share
3 answers

The way to set default details now in es6 classes is defaultProps property

So you would do something like this:

class Sample extends React.Component {
    constructor(props) {
        super(props);
        alert("In constructor");
    }
    render() {
        return <div></div>;
    }
}

Sample.defaultProps = {
   sampleProp: 'sample',
};
+2

getDefaultProps() , this.props.

, Child, prop say testProp = "this test prop". this.props.testProps. , , . getDefaultProps , , , , .

, ES5 :

getDefaultProps() {
  testProp="This is default value for test prop"
}

ES6:

Sample.defaultProps = {
   testProp: 'This is default value for test prop',
};
+1

defaultprops

static defaultProps = {
   test: "default value of test"
}
0

Source: https://habr.com/ru/post/1662902/


All Articles