클래스형 컴포넌트
- 클래스형 컴포넌트에서는 render() 메서드가 있어야한다. render() 메서드에서 렌더링하고 싶은 JSX를 반환한다. defaultProps를 사용하여 props의 default 값을 설정한다.
class App extends React.Component {
render() {
const { name } = this.props;
return <div>Hello {name}</div>;
}
}
App.defaultProps = {
name: '이름 없음'
}
export default App;
- this 키워드를 사용하려면 생성자 함수 안에 super(props)를 선언해야한다. super(props)를 선언함으로써 constructor 사이클이 끝나기전 this.props의 생성되는 것을 보장한다.
class App extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
}
render() {
const { name } = this.props;
return <div>Hello {name}</div>;
}
}
class App extends React.Component {
constructor(props) {
super();
console.log(this.props);
}
render() {
const { name } = this.props;
return <div>Hello {name}</div>;
}
}
- 클래스형 컴포넌트 여러 종류의 생명주기 메서드를 갖는다.
class App extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
componentDidUpdate(prevProps, prevState, snapshot) {
}
componentWillUnmount() {
}
shouldComponentUpdate(nextProps, nextState) {
}
render() {
const { name } = this.props;
return <div>Hello {name}</div>;
}
}
export default App;
- constructor()는 해당 컴포넌트 마운트되기 전에 호출된다. 보통 this.state에 객체를 할당하여 초기화하거나 이벤트 메서드를 바인딩한다.
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
- componentDidMount() 컴포넌트가 마운트된 직후, 즉 트리에 삽입된 후에 호출된다. DOM노드가 있어야 하는 초기화 작업을 이 메서드에서 진행하면 된다.(데이터 요청, setState()호출)
componentDidMount() {
ajax...
this.setState(...)
}
- componentDidUpdate()는 최초의 렌더링에서는 호출되지 않는다. 컴포넌트가 갱신되었을 때 DOM을 조작하거나 이전과 현재의 props를 비교하기 위해 활용된다.
componentDidUpdate(prevProps) {
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
- componentWillUnmount()는 컴포넌트가 마운트 해제되어 제거되기 전에 호출된다. 이 메서드 안에서 이벤트 제거, 네트워크 요청 취소 등의 작업을 수행한다.
componentWillUnmount(){
Btn.removeEventListener(...)
}
- shouldComponentUpdate()를 사용하면 현재 state 또는 props가 새로운 값으로 갱신되어 렌더링이 발생하기 직전에 호출된다.
- False를 반환할 경우 render(),componentDidUpdate()를 호출하지 않음
shouldComponentUpdate(nextProps, nextState){
return nextProps === nextState
}
함수형 컴포넌트
- 만들 컴포넌트가 라이프사이클API를 사용하지 않고 props만 전달해주는 역할일때 많이 사용한다.
const Hello = (props) => <div>hello, {props.name}</div>