A
A
Andrew2017-03-28 00:03:03
React
Andrew, 2017-03-28 00:03:03

How to correctly set initial state in es6 component?

class MyComponent extends Component {
  constructor() {
    super()
    this.state = { number: 0 }
  }
}

VS
class MyComponent extends Component {
  this.state = { number: 0 }
}

there is a difference? which option is better to use?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
Hellas, 2017-03-28
@undefined_title

What is the difference between constructor and just state?

I
Islam Ibakaev, 2017-03-28
@devellopah

if there are no methods that need to be bound in the constructor, then you can do this

class MyComponent extends React.Component {

  static propTypes = {}

  static defaultProps = {}

  state = { number: 0 }

  componentDidMount() {}

  method1() {}

  // et cetera
}

U
UsulPro, 2017-03-28
@UsulPro

Here is an example from the official guide

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question