본 게시글은 노마더코더의 ReactJS로 영화 웹서비스 만들기 코스를 수강하며 정리한 글입니다.
State
데이터가 저장되는 공간
바뀌길 원하는 데이터가 저장되는 공간.
+) React에서는 태그 전체(부모 태그 포함)가 아니라 오직 바뀐 부분만 업데이트 된다.
+) {counter}로 변수 포함 가능
useState() -> [data, function]
const data = React.useState()
React에서 데이터를 담는 방법
const data = React.useState()로 data와 data를 바꾸는 setState function 지정 가능, 초기값 역시 지정 가능하다.
State를 사용하겠다! State를 생성, 부여하는 기능
+) 배열 성분에 이름을 지정하는 방법
const food = ["Hello", "hi"]
const [myFirstHello, mySecondHello] = food;
//myFirstHello = "Hello" = food[0]
//mySecondHello = "hi" = food[1]
food[0]을 myFirstHello로 지칭
food[1]을 mySecondHello로 지칭
ex) const [initData, setInitData] = React.useState(0);
function은 데이터가 바뀌면 우리가 render함수를 호출해주지 않아도 자동으로 리렌더링해준다.
(바뀐 부분을 업데이트해주기 위해 render() 함수를 사용할 수도 있지만 이는 그리 추천되지 않는다.)
current
현재 값을 통해 다음 값을 계산해야하고 싶다면 function의 첫번째 성분으로
setCounter((current) => current + 1);
과 같이 설정해줄 수 있다.
이는 setCounter(counter + 1); 과 같은 동작을 하는 코드이나
다른 곳에서 State의 값이 바뀔 시 내 State의 값이 의도하지 않은 값이 나오는 경우를 미연에 방지할 수 있다.
(setState function 내에서 current를 사용하면 data가 무엇인지 명시해주지 않아도
자동으로 function과 연결된 data를 가져오는 듯하다)
(for, htmlFor), (class, className)
JSX는 html과 비슷해보일지라도 자바스크립트이기 때문에 예약어가 존재한다.
따라서 자바스크립트에서 사용 중인 for과 html에서의 for이 혼동될 수 있기 때문에 구분된다.
class, className 역시 마찬가지이다.
ReactJS의 Event
const onChange = (event) => {
console.log(event.target.value);
};
ReactJS는 자바스크립트와 거의 같기 때문에 Event를 발생시키나 Synthetic Event(합성 이벤트)를 발생시킨다.
내부에는 target이 있는데 바뀐 input을 말함.
+) 자바스크립트 조건문
flipped === true
정확히는 ===는 자료형까지 같음을 의미한다.
+) 변수 3항 연산자
{value)>{Condition?true:false}
JSX에서의 자바스크립트
jsx에서 중괄호 {}를 통해 내부에 자바스크립트를 작성할 수 있다.
{index === "0" ? <MinunitesToHours /> : <KMtoMiles>}
2019 버전 강의를 들으며 추가한 내용입니다.
리액트에는 2가지 component가 있는데 바로 Function Component와 Class Component이다.
(이는 2021년 강의 버전에 따르면 useState, useEffect와 같은 Hook을 통해 Function Component로 통합할 수 있다.)
Function Component
import React from "react";
function App() {
return (
<div>
<span>I m function component</span>
</div>
);
}
export default App;
function component는 return 값으로 html을 반환한다.
react는 return된 html을 그려준다.
Class Component
import React from "react";
class App extends React.Component {
render() {
return <h1>I m a class component</h1>;
}
}
export default App;
class component에는 return이 없다. 왜? function이 아니라 class니까.
그래서 class component는 React.Component로부터 상속받은 render 함수를 통해 html을 그려준다.
react는 자동적으로 모든 class component의 render 함수를 실행하고자 하기 때문에
render 함수를 통해 html을 그려줄 수 있는 것이다.
import React from "react";
class App extends React.Component {
state = {
count: 0
};
render() {
return <h1>I m a {this.state.count}</h1>;
}
}
export default App;
그렇다면 왜 class component를 써야할까?
바로 class component를 통해서만 state를 사용할 수 있기 때문이다.
state는 React.Component로부터 상속받은 object고 이는 당연하게도 function에서는 사용할 수 없다.
그래서 우리가 state를 사용하기 위해서는 function component가 아닌 class component로 접근해야한다.
(다시 한번 말하지만 이젠 Hook을 통해 Function Component로 통합할 수 있다. => More 함수형 프로그래밍!)
setState()
(2021버전에서는 Hook으로 대체)
import React from "react";
class App extends React.Component{
state = {
count : 0
};
add = () => {
this.setState(current => ({ count : current.count + 1}));
};
render() {
return (
<div>
<span>{this.state.count}</span>
<button onClick={this.add}>Add</button>
<div>
);
}
}
state 내에 있는 변수를 수정할 때 직접 수정하지 말라!
add 함수 부분을 보면 setState를 호출하여 current로 현재 state를 불러와 state의 count를 증가시키는 모습을 보여준다.
state 내의 변수를 직접 지정하는 것이 아닌 setState로 바꿔주어야 한다.
Component Life Cycle
(2021버전에서는 Hook으로 대체)
먼저 Component Life Cycle은 다음과 같다.
1. Mounting : 생성하는 것
2. Updating : 업데이트 하는 것( = setState 호출)
3. Unmounting : 없애는 것 (다른 페이지로 이동, component 교체)
모든 Component는 이 과정을 거치며 생성되고 사라진다.
component에서 사용하는 method는 render 뿐이지만 React.Component는 life cycle method를 가진다.
Life cycle method란 react가 component를 생성(Mount)하고 업데이트(Update)하고 없애는(Unmout) 방법이다.
그래서 component가 생성될 때, 즉 render되기 전에 실행되는 몇 가지 함수가 있고
render 후에 실행되는 몇 가지 함수가 있다. 이 함수들을 알아보자.
1. Mounting
1. constructor() : React가 아닌 JS에서 클래스가 생성될 때 호출되는 함수이다. render 전에(생성 시) 호출됨.
2. static getDrivedStateFromProps()
3. render() : render 함수
4. componentDidMount() : render 후에 실행되는 함수이다. component가 생성(Mount)되면 호출된다.
2. Updating
1. static getDrivedStateFromProps()
2. shouldComponentUpdate()
3. render() : render 함수
4. getSnapshotVeforeUpdate()
5. componentDidUpdate() : render 후(update 후) 실행되는 함수이다. Component가 update되면 호출된다.
3. Unmounting
1. componentWillUnmount() : conponent가 unmout되기 전에 호출된다.
'Frontend > React' 카테고리의 다른 글
[React] 6. React Router (0) | 2021.11.25 |
---|---|
[React] 5. Effect (0) | 2021.11.24 |
[React] 4. CREATE REACT APP (0) | 2021.11.24 |
[React] 3. Props (0) | 2021.11.23 |
[React] 1. Basic of React (0) | 2021.11.23 |