함수 컴포넌트와 클래스 컴포넌트
컴포넌트를 정의하는 가장 간단한 방법은 JavaScript 함수를 작성하는 것입니다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
이 함수는 데이터를 가진 하나의 “props” (props는 속성을 나타내는 데이터입니다) 객체 인자를 받은 후 React 엘리먼트를 반환하므로 유효한 React 컴포넌트입니다. 이러한 컴포넌트는 JavaScript 함수이기 때문에 말 그대로 “함수 컴포넌트”라고 호칭합니다.
또한 ES6 class를 사용하여 컴포넌트를 정의할 수 있습니다.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
React의 관점에서 볼 때 위 두 가지 유형의 컴포넌트는 동일합니다.
클래스에 사용하는 특별한 메서드
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() { }
componentWillUnmount() { }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
componentDidMount() : 컴포넌트 출력물이 DOM에 렌더링 된 후 실행됩니다.
componentWillUnmount() : 컴포넌트가 화념에서 사라지는 순간 실행됩니다.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() { this.setState({ date: new Date() }); }
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
State를 올바르게 사용하기
setState()에 대해서 알아야 할 세 가지가 있습니다.
직접 State를 수정하지 마세요
예를 들어, 이 코드는 컴포넌트를 다시 렌더링하지 않습니다.
// Wrong
this.state.comment = 'Hello';
대신에 setState()를 사용합니다.
// Correct
this.setState({comment: 'Hello'});
this.state를 지정할 수 있는 유일한 공간은 바로 constructor입니다.
State 업데이트는 비동기적일 수도 있습니다.
React는 성능을 위해 여러 setState() 호출을 단일 업데이트로 한꺼번에 처리할 수 있습니다.
this.props와 this.state가 비동기적으로 업데이트될 수 있기 때문에 다음 state를 계산할 때 해당 값에 의존해서는 안 됩니다.
예를 들어, 다음 코드는 카운터 업데이트에 실패할 수 있습니다.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
이를 수정하기 위해 객체보다는 함수를 인자로 사용하는 다른 형태의 setState()를 사용합니다. 그 함수는 이전 state를 첫 번째 인자로 받아들일 것이고, 업데이트가 적용된 시점의 props를 두 번째 인자로 받아들일 것입니다.
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
위에서는 화살표 함수를 사용했지만, 일반적인 함수에서도 정상적으로 작동합니다.
// Correct
this.setState(function(state, props) {
return {
counter: state.counter + props.increment
};
});
State 업데이트는 병합됩니다
setState()를 호출할 때 React는 제공한 객체를 현재 state로 병합합니다.
예를 들어, state는 다양한 독립적인 변수를 포함할 수 있습니다.
constructor(props) {
super(props);
this.state = {
posts: [], comments: [] };
}
별도의 setState() 호출로 이러한 변수를 독립적으로 업데이트할 수 있습니다.
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts });
});
fetchComments().then(response => {
this.setState({
comments: response.comments });
});
}
병합은 얕게 이루어지기 때문에 this.setState({comments})는 this.state.posts에 영향을 주진 않지만 this.state.comments는 완전히 대체됩니다.
setState 는 살짝 이벤트 트리거? 같은 역활을 하는듯 하다.
'공부 > react' 카테고리의 다른 글
[REACT] Element Rendering (0) | 2022.11.09 |
---|---|
[REACT] JSX (0) | 2022.11.09 |