Why is getInitialState not being called for my React class?

后端 未结 3 1229
无人共我
无人共我 2021-02-01 15:20

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

import { Component } from \'react\';

export default class MyReactComponent ext         


        
相关标签:
3条回答
  • 2021-02-01 15:46

    The developers talk about ES6 class support in the Release Notes for v0.13.0. If you use an ES6 class that extends React.Component, then you should use a constructor() instead of getInitialState:

    The API is mostly what you would expect, with the exception of getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.

    0 讨论(0)
  • 2021-02-01 15:54

    Code to accompany Nathans 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>
        );
      }
    }
    
    0 讨论(0)
  • 2021-02-01 16:11

    To expand a bit on what it means

    getDefaultProps and propTypes are really just properties on the constructor.

    the "on the constructor" bit is weird wording. In normal OOP language it just means 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 within the class like:

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

    or with anything you declare as a static class variable. I don't know why this is not talked about anywhere online with regards to ES6 classes :?

    see the docs.

    0 讨论(0)
提交回复
热议问题