Answer the question
In order to leave comments, you need to log in
How to correctly set initial state in es6 component?
class MyComponent extends Component {
constructor() {
super()
this.state = { number: 0 }
}
}
class MyComponent extends Component {
this.state = { number: 0 }
}
Answer the question
In order to leave comments, you need to log in
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
}
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 questionAsk a Question
731 491 924 answers to any question