Today I Learned 2023.03.10. [React 심화1]

Dongchan Alex Kim·2023년 3월 10일
0

Today I Learned

목록 보기
4/31
post-thumbnail

Redux ToolKit

Redux ToolKit은 리덕스를 개량하여 만든 것으로 생각하면 된다.

yarn add react-redux @reduxjs/toolkit

//설치는 참고하세요...

가장 큰 차이점
1. Action Value 와 Action Creator를 직접 생성해주지 않는다.
2. Action Value,Action Creator,Reducer가 하나로 합쳐졌다는 점이다.

//counterSlice.js
const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    // 리듀서 안에서 만든 함수 자체가 리듀서의 로직이자, 액션크리에이터가 된다.
    addNumber: (state, action) => {
      state.number = state.number + action.payload;
    },

    minusNumber: (state, action) => {
      state.number = state.number - action.payload;
    },
  },
});

counterSlice 객체 안에서 만들어주는 함수가 리듀서의 로직을 만들어주는 동시에, Action Creator가 되면서, Action Value까지 함수의 이름을 따서 자동으로 만들어지는 것이다...!

// 액션크리에이터는 컴포넌트에서 사용하기 위해 export 하고
export const { addNumber, minusNumber } = counterSlice.actions;
// reducer 는 configStore에 등록하기 위해 export default 합니다.
export default counterSlice.reducer;

리듀서에 로직을 추가할 때마다 함수를 추가해서 내보내주면 된다.

//configStore.js

import { configureStore } from "@reduxjs/toolkit";
/**
 * import 해온 것은 slice.reducer 입니다.
 */
import counter from "../modules/counterSlice";
import todos from "../modules/todosSlice";

/*
 * 모듈(Slice)이 여러개인 경우
 * 아래 예시는 하나의 프로젝트 안에서 counter 기능과 todos 기능이 모두 있는 것이다.
 */

const store = configureStore({
  reducer: { counter: counter, todos: todos },
});

export default store;

Json-Server

단순히 mock data로 사용하는 것을 넘어, 실제로 배포까지 하여 간단한 API 서버를 구축하고 과제 프로젝트를 완성하는데 사용.

FE에서는 BE가 하고 있는 작업을 기다리지 않고, FE의 로직과 화면을 구현 할 수 있어 효율적으로 협업을 할 수 있다고 한다.

yarn add json-server

yarn json-server --watch db.json --port 4000

HTTP

서버(웹 서버)와 클라이언트(웹 브라우저)가 대화하기 위해 서로 약속된 방식을 프로토콜(protocol)이라고 한다.

  • 서로 데이터를 주고 받기 위해서는 항상 ‘요청(request)’을 해야 하고, 그에 따른 ‘응답(response)’을 뿌려준다.

상태코드

  • 1xx(정보) : 요청을 받았으며 프로세스를 계속 진행.
  • 2xx(성공) : 요청을 성공적으로 받았으며 인식했고 수용.
  • 3xx(리다이렉션) : 추가 작업 조치가 필요.
  • 4xx(클라이언트 오류) : 요청의 문법이 잘못되었거나 요청을 처리 X.
  • 5xx(서버 오류) : 서버가 명백히 유효한 요청에 대한 충족을 실패.

비동기 통신

yarn add axios
//GET
// axios를 통해서 get 요청을 하는 함수를 생성합니다.
// 비동기처리를 해야하므로 async/await 구문을 통해서 처리합니다.
  const fetchTodos = async () => {
    const { data } = await axios.get("http://localhost:3001/todos");
    setTodos(data); // 서버로부터 fetching한 데이터를 useState의 state로 set 합니다.
  };
//POST
 const onSubmitHandler = async(todo) => {
    await axios.post("http://localhost:3001/todos", todo); 
		setTodos([...todos, todo])
  };

  useEffect(() => {
    fetchTodos();
  }, []);
  1. 처음에 서버에 있는 todo만 존재한다.
  2. axios.post명령을 통해 서버에 todo가 추가되어서 todo가 두개가 된다.
  3. useEffect를 통해 fetchTodos가 다시 실행되어 todo 값을 받아옴
  4. setTodos를 새로고친다 마치 서버에서 받아온 것처럼 구라임
  5. 구라치는거 화면에 그릴 준비 완료
 const onClickDeleteButtonHandler = (todoId) => {
    axios.delete(`http://localhost:3001/todos/${todoId}`);
  };
...
<button
  type="button"
  onClick={() => onClickDeleteButtonHandler(todo.id)}>
  삭제하기
</button>
profile
Disciplined, Be systemic

0개의 댓글