state를 관리하게 될 때, useState를 사용하는 것 말고 useReducer를 사용할 수 있습니다.
Reducer 함수는 state 데이터의 수정방법을 미리 정의하는 함수입니다.
기본 형식은 아래와 같습니다.
const reducer = (state,action) => {
switch (action.type){
case "a":
return state+action.payload;
default:
return state;
}
}
const [money,dispatch] = useReducer(reducer,0)
dispatch({type:"a",payload:})
# payload ; 사용에 있어서 전송되는 데이터
# reducer ; state를 업데이트 하는 역할 / state ; reducer가 불리는 시점의 data값이 들어감 / action ; 요구의 내용
# 여기서 money ; reducer에서 return된 값이 들어갈 곳 / dispatch ; state 업데이트를 위한 요구
첫번째 예시입니다.
첫번째 예시는 useState를 이용한 코드base입니다.
import React, { useState } from "react";
const Test = () => {
const [number, setNumber] = useState(0);
return (
<div style={{ fontSize: "30px" }}>
<h2>useReducer 은행에 오신것을 환영합니다.</h2>
<p>잔고: {money}원</p>
<input
type="number"
value={number}
onChange={(e) => {
setNumber(parseInt(e.target.value));
}}
step="1000"
/>
<button>예금</button>
<button>출금</button>
</div>
);
};
export default Test;
다음은 useReducer를 활용해보겠습니다.
import React, { useReducer, useState } from "react";
const reducer = (state, action) => {
console.log("reduer가 일을 합니다!", state, action);
switch (action.type) {
case "DEPOSIT":
return state + action.payload;
case "WITHDRAW":
return state - action.payload;
default:
return state;
}
};
const Test = () => {
const [money, dispatch] = useReducer(reducer, 0);
const [number, setNumber] = useState(0);
return (
<div style={{ fontSize: "30px" }}>
<h2>useReducer 은행에 오신것을 환영합니다.</h2>
<p>잔고: {money}원</p>
<input
type="number"
value={number}
onChange={(e) => {
setNumber(parseInt(e.target.value));
}}
step="1000"
/>
<button
onClick={() => {
dispatch({ type: "DEPOSIT", payload: number });
}}
>
예금
</button>
<button
onClick={() => {
dispatch({ type: "WITHDRAW", payload: number });
}}
>
출금
</button>
</div>
);
};
export default Test;
다음에 이어서 작성할 것
https://www.youtube.com/watch?v=tdORpiegLg0
다음 예시입니다.
useState를 이용해 input요소를 만들었습니다.
import React, { useState } from "react";
const Test = () => {
const [name, setName] = useState("");
return (
<div>
<h1>출석부</h1>
<p>총 학생 수: ?</p>
<input
type="text"
placeholder="이름을 입력해주세요"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button>추가</button>
</div>
);
};
export default Test;
다음 예시입니다.
컴포넌트 바깥에 reducer함수를 정의하겠습니다.
3 : state, action이라는 매게변수 사용하겠습니다.
5 : action.type의 값에 따라 실행하겠습니다.
4/6/9/13 : action.type이 INIT이라면/REMOVE라면/EDIT라면 아래 함수 실행합니다.
INIT을 제외한 각각의 case들은 newState에 action.data와 state를 이용해 newState변수를 만들어 최종적으로 newState를 return하였습니다.
import { useReducer } from "react";
const reducer = (state, action) => {
let newState = [];
switch (action.type) {
case "INIT":
return action.data;
case "CREATE":
newState = [action.data, ...state];
break;
case "REMOVE": {
newState = state.filter((it) => it.id !== action.targetId);
break;
}
case "EDIT": {
newState = state.map((it) =>
it.id === action.data.id ? { ...action.data } : it
);
break;
}
default:
return state;
}
return newState;
};
2 : useReducer함수를 정의합니다.
형식은 const [state,dispatch] = useReducer(reducer, initialState); 입니다.
useState와 형식이 비슷합니다. const [state,setState] = useState(initialState); 에서 reducer함수만 추가해준 형태입니다.
dispatch()를 사용하면 HTML 안에서 reducer함수를 동작시킬 수 있습니다.
dispatch({type:데이터수정방법, dasa:전달할데이터})을 지정해주면됩니다.
-> 8~13 : 위 코드 9째 줄에서 볼 수 있듯이 action.data로 받습니다.
-> 21 : 위 코드 12째 줄에서 볼 수 있듯이 action.targetId로 받습니다.
-> 28~33 : 위 코드 17째 줄에서 action.data.id로 받습니다.
function App() {
const [data, dispatch] = useReducer(reducer, []);
const dataId = useRef(6);
// CREATE
const onCreate = (date, content, emotion) => {
dispatch({
type: "CREATE",
data: {
id: dataId.current,
date: new Date(date).getTime(),
content,
emotion,
},
});
dataId.current += 1;
// localStorage.setItem(JSON.stringify({data.id:23}));
};
// REMOVE
const onRemove = (targetId) => {
dispatch({ type: "REMOVE", targetId });
};
// EDIT
const onEdit = (targetId, date, content, emotion) => {
dispatch({
type: "EDIT",
data: {
id: targetId,
date: new Date(date).getTime(),
content,
emotion,
},
});
};
}
'WebProgramming > React' 카테고리의 다른 글
[React] Checkbox 값 제어하기 (0) | 2022.07.17 |
---|---|
[React] 한 페이지 정리 (0) | 2022.07.17 |
[React] Component로 css요소 복사하기 (0) | 2022.07.17 |
[React] 웹사이트 배포하기 (0) | 2022.07.13 |
[React] Redux (0) | 2022.07.09 |
[React] useContext를 이용해 전역 props전달하기 (0) | 2022.07.09 |
[React] useParams를 이용해 파라미터 가져오기 (0) | 2022.07.09 |
[React] 자식 Component에서 부모 Componet로 값 변경하여 전달하기 (0) | 2022.07.09 |