class TempComponent extends Component{
constructor(props){
super(props);
}
render(){
return(<></>);
}
}
React에서 Component를 생성할 때 state 값을 초기화하거나 메서드를 바인딩할 때 construcotr()를 사용합니다. React의 Component의 생성자는 해당 Component가 마운트 되기 전 호출됩니다. React.Component를 상속한 컴포넌트의 생성자를 구현할 때는 super(props)를 선언을 권고하고 있습니다. 이유는 this.props 사용 시 생성자 내에서 정의되지 않아 버그 발생 가능성이 생기기 때문입니다.
class TempComponent extends Component{
constructor(props){
super(props);
this.setState({counter: 0}) (X)
this.state = {counter: 0} (O)
}
render(){
return(<></>);
}
}
constructor()를 사용할때 흔히 사용하는 실수는 setState를 호출하는 것입니다. 생성자 내에서는 setState를 사용하는 것이 아닌 this.state로 초기값을 할당해주어야 합니다. 생성자는 this.state를 직접 할당할 수 있는 곳으로 그 외에는 꼭 this.setState()를 사용하세요.
생성자 내에서는 구독 작업이나 외부 API 호출을 하면 안 됩니다. 안 됩니다. 외부 API 호출이 필요하다면 componentDidMount()를 사용하세요. 혹시 componentWillMount()를 사용하시던 분들이라면 componentDidMount()로 함수를 수정해주세요. 현재 React에서 componentWillMount를 삭제 예정이므로 이제 이 함수를 사용하면 안 됩니다.
class TempComponent extends Component{
constructor(props){
super(props);
this.state = { color : props.color } (O)
}
render(){
return(
<div>{this.state.color}<div/> (x)
<div>{this.props.color}<div/> (o)
);
}
}
흔히 하는 실수가 props로 전달된 값을 state로 복사하는 것입니다. state로 복사하여 사용하면 버그를 발생할 수 있고 props가 변하더라도 state는 업데이트가 되지 않습니다.
class TempComponent extends Component{
constructor(props){
super(props);
this.state = { color : props.color } (O)
}
componentWillReceiveProps(nextProps){ (x)
this.setState({color : nextProps.color});
}
render(){
return(
<div>{this.state.color}<div/> (x)
<div>{this.props.color}<div/> (o)
);
}
}
그래서 일부 잘못된 생각으로 componentWillReceiveProps()나 componentWillUpdate()를 사용하여 state와 props를 다시 복사하는 코드를 작성하시는 분들이 있습니다. 절대 이렇게 사용하시면 안 됩니다. setState를 하기 때문에 추가 랜더링을 발생하여 성능상 이슈가 있을 수 있으며 버그를 발생시킬 수 있습니다. 또한 componentWillReceiveProps()는 React의 17 버전부터는 삭제될 예정입니다. 이럴 때는 this.props를 바로 사용하세요.
props값을 state로 복사하여 사용하는 경우는 props 초기 값을 저장해서 사용할 때만 복사해서 사용합니다.
'Node.js' 카테고리의 다른 글
Nodejs Express MariaDB(Ubuntu) 회원가입 및 로그인 (1) (0) | 2021.12.21 |
---|---|
[MERN] SNS Chat App 만들기 (1) (0) | 2021.11.24 |
[Node.js] Express Server 구축 (0) | 2021.11.09 |
[Node.js/vue.js] 영화정보 페이지 제작(frontend, backend 연동) (0) | 2021.09.17 |
[Node.js] 템플릿엔진 (0) | 2021.09.14 |