State
State : 리액트 컴포넌트의 상태
→ 리액트 컴포넌트의 변경 가능한 데이터를 state라고 한다.
렌더링이나 데이터 흐름에 사용되는 값만 state에 포함 시켜야 한다!
State 특징
Just 하나의 자바스크립트 객체이다.
→ state는 자바스크립트 객체
Ex)
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = {
liked: false
};
}
}
LikeButton이라는 컴포넌트이다. 모든 클래스 컴포넌트에는 constructor라는 이름의 함수가
존재하는데 생성자라는 의미를 가지고 있으며, 클래스가 생성 될 때 실행되는 함수이다.
이 생성자 코드 내에 this.state라는 부분이 현재 컴포넌트의 state를 정의하는 부분이다.
클래스 컴포넌트는 state를 생성자에서 정의하고,
함수 컴포넌트에서는 useState()라는 훅을 사용한다.
State는 정의된 후 일반적인 자바스크립트 변수처럼 직접 수정할 수 없다.
// state를 직접 수정 (잘못된 사용법)
this.state = {
name: 'Kim'
};
// setState 함수를 통한 수정 (정상적인 사용법)
this.setState({
name: 'Kim'
});
수정하는 방법
- state를 직접 수정하는 방법
- setState() 함수 이용하여 수정
state를 직접 수정할 수 있지만 리액트가 수정된 것을 제대로 인식하지 못할 수 있어서
직접적인 변경은 불가능하다고 생각하는 것이 좋다.
실습 (State 함수 사용해보기)
1. chapter_06 디렉토리 생성 후 Notification.jsx 생성
2. Notification 컴포넌트 생성
import React from "react";
const styles = {
wrapper: {
margin: 8,
padding: 8,
display: "flex",
flexDirection: "row",
border: "1px solid grey",
borderRadius: 16,
},
messageText: {
color: "black",
fontSize: 16,
},
};
class Notification extends React.Component {
constructor(props){
super(props);
this.state = {};
}
render() {
return(
<div style={styles.wrapper}>
<span style={styles.messageText}>
{this.props.message}
</span>
</div>
);
}
}
export default Notification;
3. Notification 컴포넌트는 state에 아무런 데이터가 없기 때문에 NotificationList.jsx(목록 형태로 보여주기 위함)
import React from "react";
import Notification from "./Notification";
const reservedNotifications = [
{
message: "하이, 오늘 일정은요~",
},
{
message: "노팅엄 화이팅",
},
{
message: "이제 곧 경기가 시작됩니다.",
},
];
var timer;
class NotificationList extends React.Component{
constructor(props){
super(props);
this.state = {
notifications: [],
};
}
/**
notifications라는 이름의 배열을 state에 삽입 후
클래스 컴포넌트 생명 주기 함수 중에 하나인 componentDidMount () 함수에서
sertInterval() 함수를 사용하여 매 1000ms(1초) 마다 정해진 작업을 수행
**/
componentDidMount() {
const { notifications } = this.state;
timer = setInterval(() =>{
if(notifications.length < reservedNotifications.length) {
const index = notifications.length;
notifications.push(reservedNotifications[index]);
this.state({
notifications: notifications,
});
} else {
clearInterval(timer);
}
}, 1000);
}
render() {
return (
<div>
{this.state.notifications.map((Notification) => {
return <Notification message={Notification.message} />;
})}
</div>
);
}
}
export default NotificationList;
4. index.js 수정 후 npm start 실행
<출처> 소플의 처음 만난 리액트 (저) 이인제 한빛미디어
'Front-End > React' 카테고리의 다른 글
[React] 훅 (0) | 2022.09.03 |
---|---|
[React] 생명 주기 (0) | 2022.09.03 |
[React] 컴포넌트와 Props (0) | 2022.08.19 |
[React] Element (0) | 2022.08.16 |
[React] JSX (0) | 2022.08.13 |