Front-end/React.js

3. State - 웹 서비스 만들기 | 노마드코더

AGAL 2020. 3. 8. 17:25
반응형

[출처 : https://academy.nomadcoders.co]

0. Class Components and State

# state : 동적 데이터와 함께 작업할 때 만들어지는 변하는 데이터.    *Dynamic data

 - state는 object이다. component의 data를 넣을 공간이 있으며, 바꾸고 싶은 date를 넣는다.

 

# state를 사용하려면 function component가 아닌 class componet를 이용한다.

// class App은 React.Component에서 확장되어서 class React의 특성을 사용할 수 있게 된다. 
class App extends React.Component{
  // return이 아닌 render 메소드를 사용한다.
  render(){
  
  }
}
// 버튼이 클릭됐을 때만 add function이 호출된다.
<button onClick={this.add}>Add</button>
// minus function이 즉시 호출된다.
<button onClick={this.minus()}>Minus</button>

1. All you need to know about State

# state를 직접 변경하면 react는 render function을 refresh하지 않기 때문에 직접 변경하면 안된다.   

 

# setState fuction을 호출하면 react는 state의 값이 변경(refresh)되면서 render function을 다시 호출한다.

 * this.setState({ state속성 : 변경값 })

add = () => {
  // this.state : state에 의존하는 것은 몇가지 성는 문제가 있어서 좋지 않은 방법
  this.setState({count : this.state.count +1 });
}
minus = () => {
  // current=>() : state를 set할 때, react에서 외부의 상태에 의존하지 않는 가장 좋은 방법
  this.setState(current => ({count : current.count +1 }));
}

2. Component Life Cycle

# Mounting

 : component가 screen에 표시될 때,

 - component가 mount될 때, constructor를 호출한다. 그리고 나서 render 한다.

 - componentDidMount() : component가 render할 때, 해당 component가 처음 render를 호출한 다음 실행

 

# Updating

 : component가 update 될 때    *ex) setState()로 state의 값이 변경될 때.

 - shouldComponentUpdate() : 기본적으로 업데이트를 할지 말지를 결정한다.

 - componentDidUpdate() :  setState()가 호출되면 component를 호출하고, 먼저 render를 호출한 다음 업데이트가 완료되면 실행 

 

# Unmounting

 : compnent가 떠날 때    *ex) 다른 페이지로 갈 때

 - componentWillUnmount() : component가 마운트 해제되어 제거되기 직전에 실행


3. Planning the Movie Component

 

# componentDidMount에서 data를 fetch 한다. ⇒ API로 부터 data fetching이 완료되면 Render 한다.

 

# setState()를 사용할 때 state 안에 default 값을 선언할 필요는 없다.

반응형