React class형 컴포넌트

hwakyungChoi·2020년 9월 18일
0
  • class 형 컴포넌트는 여전히 어렵다.
import React from "react";

export default class App extends React.Component {
	constructor(props){
    	super(props)
      	this.state ={
        	name:"pandaman",
          	age : 27,
          	job:"PM"
          
        }
      
      render
    }
  
  redner(){
  	const {name,age,job} = this.state;
    
    return (
    	<div>
      	<div>name:{name}</div>
		<div>age:{age}</div>
		<div>job:{job}</div>
      </div>
    )
  }
}
  • class에 extends 키워드를 통해 상속받을 클래스를 명시

  • constructor 생성자 내부에 super()연산자를 사용해 React.Component를 상속받아 this.state을 사용 가능

  • setState()
    - state를 변경하기 위해 setState()함수를 사용해야 함 비동기로 작동됨

    • 즉시 반영이 안된다는 뜻
    • 1) setState(updater,[callback]
    • 2) updater:(state,props) => stateChange
      updater 함수로 전달된 state, prop는 최신의 값으로 상태를 업데이틀 함
      두 번재째 인수인 callback은 setState의 실행이 완료되고 컴포넌트가 렌더링된 뒤에 실행될 함수
onAgeHandler = () => {
	this.steState((state) => {age:state.age +1})
}

onAgeHandler = () => {
  const {age} = this.state;
	this.steState({age:age +1})
}


//age가 업데이트되면 callback 작동하여 업데이트된 age가 로그에 남기게 됨
onAgeHandler = () => {
  
	this.steState(prevState => ({
    	age:prevSTate.age + 1
    }),
    () => console.log(this.state.age)
   );
}

출처 : https://oyg0420.tistory.com/entry/Reactjs-%EB%A6%AC%EC%95%A1%ED%8A%B8-state%EC%99%80-props

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN