Is it better to define state in constructor or using property initializers?

会有一股神秘感。 提交于 2019-11-26 18:43:13

They are equivalent because class field proposal is syntactic sugar for constructor body code.

In case there's no need for explicit constructor (creating temporary local variables, etc), constructor can be omitted in favour of class fields.

The problem with explicit constructor is that super arguments (props) are often omitted by mistake, this may result in problems:

constructor() {
    super();
    this.state = { foo: this.props.foo } // this.props is undefined
}

Explicit constructor may beneficial for readability. Methods are conventional placed below constructor, even arrow properties. This won't work as intended because class fields are assigned in the order they were listed:

state = { foo: { method: this.someMethod } } // this.someMethod is undefined

someMethod = () => ...;

In this case explicit constructor may result in more readable code:

constructor(props) {
    super(props);

    // <-- this is the place where this.someMethod is really assigned

    this.state = { foo: { method: this.someMethod } }
}

someMethod = () => ...;

Dan's code actually has a subtle bug which is why I recommend using the initializers whenever possible. React component constructors take two arguments - props and the context. He's not passing it to the parent constructor and it could easily be missed by some other developer who needed it.

Sometimes you have no choice, like when the initializer depends on the constructor arguments, so just remember to pass all the arguments to the parent.

After trying a few things, looks like React doesn't have the issue I was thinking of. You can pass whatever you want to the parent constructor and it will be fine. E.g.:

class MyComponent extends React.Component {
  constructor(props) {
    super({})
  }

  render() {
    // this.props will still be set correctly here
  }
}

I still recommend using the initializers as not having to call the parent constructor is one less thing to think about.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!