-
#3.State프론트엔드/react(노마드코더) 2020. 2. 19. 14:56
1. state 를 사용하기 위해서는 먼저, App 컴포넌트를 function 기반에서 class 기반으로 바꾸주어야 한다. state를 사용 하는 이유는 컴포넌트의 data를 동적으로 바꿔주기 위함이다.
먼저, Add 버튼과 Minus 버튼 클릭 시 console.log에 add 와 minus가 찍히게 하는 구조이다.
눈으로 따라가다보면 이해할 수 있다.
import React from "react"; import PropTypes from "prop-types"; class App extends React.Component { state = { count: 0 }; add = () => { console.log("add") }; minus = () => { console.log("minus") }; render() { return ( <div> <h1>The number is : {this.state.count}</h1> <button onClick={this.add} >Add</button> <button onClick={this.minus}>Minus</button> </div> ) } } export default App;
2. setState를 통해, 다른 곳에서 state값을 변경해줄 수 있다. 이때 반드시 setState를 사용해주어야 한다.
만약 다른 곳에서 this.state.~~ 를 입력하면 에러가 발생된다. setState를 통해 리액트에서는 state를 다시 refresh해주고,
그 refresh된 값을 다시 render 해준다.
아래 흐름을 보면
1) 화면에 보여지는 부분은 state값의 count 부분이다 (초기 값 : 0)
2) add 및 minus 버튼을 클릭하면 add 함수 및 minus 함수가 실행 된다.
3) add 함수 및 minus함수의 동작은 setState를 통해 state값을 변경해주는데, current는 현재 App 클래스 안에 있는 state를 뜻한다. setState 이후 변경값에 대해 직접 this.state.count을 입력해도 동작은 하지만 올바르지 않다.
import React from "react"; import PropTypes from "prop-types"; class App extends React.Component { state = { count: 0 }; add = () => { this.setState(current => ({ count: current.count + 1 })) }; minus = () => { this.setState(current => ({ count: current.count - 1 })) }; render() { return ( <div> <h1>The number is : {this.state.count}</h1> <button onClick={this.add} >Add</button> <button onClick={this.minus}>Minus</button> </div> ) } } export default App;
3. 컴포넌트의 life cycle
아래 코드가 실행 될 때 컴포넌트의 life cycle을 설명하자면
1) render 함수 실행
2) componentDidMount 함수 실행
3) state 업데이트 시 --> componentDidUpdate 함수 실행
4) 컴포넌트 삭제 시 --> componentWillUnmount 함수 실행
import React from "react"; import PropTypes from "prop-types"; class App extends React.Component { state = { count: 0 }; add = () => { this.setState(current => ({ count: current.count + 1 })) }; minus = () => { this.setState(current => ({ count: current.count - 1 })) }; componentDidMount() { console.log("component rendered") } componentDidUpdate() { console.log("component updated!") } componentWillUnmount() { console.log("good bye react!") } render() { console.log("rendering"); return ( <div> <h1>The number is : {this.state.count}</h1> <button onClick={this.add} >Add</button> <button onClick={this.minus}>Minus</button> </div> ) } } export default App;
4. 위 3번을 응용하여 아래와 같이 진행 할 수 있다.
먼저, this.state.isLoading을 사용하는 대신에 es6 버전으로 새롭게 도입된 방법으로 진행 하였다.
흐름은 아래와 같다.
1) render에서 this.state.isLoading 값이 true면 Loading... 의 값이 화면에 표시 된다. 그리고 false면 We are ready가 보여진다. 먼저 초기값은 true 이기 때문에 Loading이 먼저 화면에 보여진다. 동시에 componentDidMount함수가 실행 된다.
2) componentDidMount함수 내용은 setTimeout 함수가 내장되어 있는데, 6초 후 this.state.isLoading 값을 false로 바꿔주는 내용이다. 따라서, 6초 뒤에는 화면에 We are ready 문구가 표시 된다.
**이를 응용하여 state값에 새로운 key값을 정의하고, DidMount부분에 이를 호출하는 식으로 API 값을 fetch해 올 수 있다.
import React from "react"; class App extends React.Component { state = { isLoading: true }; componentDidMount() { setTimeout(() => { this.setState({ isLoading: false }) }, 6000); } render() { const { isLoading } = this.state; return ( <div> {isLoading ? "Loading..." : "We are ready"} </div> ) } } export default App;
'프론트엔드 > react(노마드코더)' 카테고리의 다른 글
#4 Making the Movie App (0) 2020.02.19 #2 JSX & Props (0) 2020.02.18 #1 setup (0) 2020.02.18