[javascript] 리액트 프레임워크에서 상태 초기화를 어떻게 처리하나요?
리액트는 컴포넌트의 상태를 초기화하는 다양한 방법을 제공합니다. 여기에는 constructor
메서드를 사용한 초기화, componentDidMount
라이프사이클 메서드를 사용한 초기화, 그리고 함수형 컴포넌트에서의 초기화 방법이 포함됩니다.
constructor
메서드를 사용한 초기화: ```javascript class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; }
// … }
`constructor` 메서드를 사용하여 `this.state` 객체에 초기 상태를 설정할 수 있습니다.
2. `componentDidMount` 라이프사이클 메서드를 사용한 초기화:
```javascript
class MyComponent extends React.Component {
state = {
count: 0
};
componentDidMount() {
this.setState({ count: 10 });
}
// ...
}
componentDidMount
메서드는 컴포넌트가 마운트된 후에 호출됩니다. 이 메서드 내에서 setState
함수를 사용하여 초기 상태를 설정할 수 있습니다.
- 함수형 컴포넌트에서의 초기화: ```javascript import React, { useState, useEffect } from ‘react’;
const MyComponent = () => { const [count, setCount] = useState(0);
useEffect(() => { setCount(10); }, []);
// …
}
```
useState
훅을 사용하여 count
상태를 선언하고 setCount
함수를 사용하여 초기 상태를 설정할 수 있습니다. useEffect
훅을 사용하여 컴포넌트가 마운트된 후에 호출되는 콜백 함수에서 초기화를 처리할 수 있습니다.
위의 세 가지 방법을 사용하여 리액트 컴포넌트의 상태를 초기화할 수 있습니다. 각각의 방법은 다소 다른 상황에 적합하지만, 일반적으로는 constructor
메서드를 사용한 초기화가 가장 일반적인 방법입니다.