
We have to define class component not function component to use "state" and "lifecycle method."
Here's a example.
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>
);
}
}
To understand this code, we need look into constructor()and super(). constructor()is used to create or initialize object made by class. It receive arguments and set default property like state. Let's me show you example.
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
rectangle = new Rectangle(10, 5);
console.log(rectangle.name, rectangle.height, rectangle.width);
// 'Rectangle' 10 5
In other words, when we create a object by using class, we transfer arguments to constructor() method. Then, let's look into super().
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
super(length, length);
this.name = 'Square';
}
}
square = new Square(10);
console.log(square.name, square.height, square.width);
// 'Square' 10 10
If we use super(length, length), it will transfer length argument that defined when creating object(square = new Square(10)) to parent class's constructor(). So, we can use parent properties in Square().
We can use "lifecycle method" when the component is rendered to DOM or deleted from DOM etc.
componentDidMount() // when component render in DOM
componentWillUnmount() // when component is deleted from DOM
// And there are many other life cycle method
this.state.key= 'hello'; // this is wrong
this.setState({key: 'hello'}); // this is right
The only space we can modify this.state is in constructor().
// this is wrong
this.setState({
key: this.state.key + this.props.increment,
});
// this is right
this.setState((state, props) => ({
key: state.key + props.increment
}));
<App date={this.state.date} />