[ReactJS 이론] #3 State and Lifecycle

mechaniccoder·2020년 5월 25일
0

ReactJS이론

목록 보기
3/4
post-thumbnail

내용

We have to define class component not function component to use "state" and "lifecycle method."

How to add state in class component? constructor() and super()

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().

What is lifecycle method?

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

setState()

Don't fix state directly

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().

State updating is 비동기적

// this is wrong
this.setState({
	key: this.state.key + this.props.increment,
});

// this is right
this.setState((state, props) => ({
	key: state.key + props.increment
}));

Data flows to bottom

  • Any other components can't access a state except for a component that has the state.
  • Component can transfer one's state to children component.
<App date={this.state.date} />

Reference

profile
세계 최고 수준을 향해 달려가는 개발자입니다.

0개의 댓글