부트캠프 12Week

kim unknown·2022년 6월 25일
0

ELICE

목록 보기
10/11
post-thumbnail

- 220620 ~ 220621

crud의 전체적인 내용 정리와 상태 관리 훅에 대해서 학습했다. 온라인 강의 실습 내용이 유독 어려웠는 데, 기본 개념이 제대로 학습되지 않은 상태에서 코드를 짜려하니 너무 힘들었다. 그래서 결국은 혼자 블로깅 하면서 따로 개념 학습을 했다.🥲
상태관리 훅이 이렇게 많이 있는지 몰랐는 데, 각 훅들의 특성을 잘 알고 상황에 따라 잘 사용해야겠다는 생각이 들었다. 잘못하면 성능이 되려 나빠질 수도 있기 때문에..

  • useEffect는 promise를 입력값으로 받지 않는다.
  • Link의 to는 click했을 때 해당 url로 변경하라는 의미 -> a 링크와 동일
  • Route의 path는 바뀐 url과 매치되는 컨포넌트를 렌더링

  • useRef는 useState와 달리 ref의 값이 변경되어도 컴포넌트가 재렌더링되지 않는다. useRef 함수는 current 속성을 가지고 있는 ref객체를 반환한다.

  • useContext는 state를 컴포넌트 간에 전역적으로 공유하여 사용할 수 있다. createContext로 context 객체를 생성할 수 있고, 생성된 context 객체는 Provider를 통해 하위 컴포넌트에게 전달될 수 있다.
  • context = createContext(default value) 컨텍스트 생성
  • <context.Provider value={provider value}> 컨텍스트로부터 컴포넌트 생성
  • contextValue = useContext(context) context의 값을 불러옴 -> 가까운 Provider의 영향을 받음

  • useReducer는 useState와 똑같이 상태 관리를 하지만, 보다 복잡한 상태 관리에 유리하다.
  • 다음 state가 이전 state에 의존적인 경우에 보통 useState보다 useReducer를 사용하는 것이 좋다.
  • const [state, dispatch] = useReducer(reducer, initialArg, init)
  • useReducer를 은행으로 비유
const initialState = {count: 0};
// reducer는 은행
// state는 현재 장부 값, action은 사용자가 시킨 행동
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      // return 값이 state 값이 됨
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}
// state는 장부 값
// dispatch는 창구 직원, dispatch를 부르면 reducer 함수 실행
// initialState는 state의 초기값
function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

- 220622 ~ 220623

리덕스에 대해서 배웠는 데 너무너무너무 어려웠다. 아직 상태관리 훅에도 익숙해지지 않았는 데 리덕스까지 배우려니 너무 힘들었다.. 리덕스랑 리액트 리덕스랑 리덕스 툴킷을 한 번에 배우려니 너무 혼동이 왔다😱 그래도 리덕스는 중요한 개념이니 잘 챙겨가야겠다는 생각이 들었다.

  • Redux: 전역적으로 상태 관리
  • npm install redux react-redux redux 설치
  • 하나의 store에 모든 state를 저장하고 관리 -> createStore
  • import { createStore } from "redux";
  • const store = createStore(reducer, initialState);;
  • import store from "./Store";
    Store.js
import { createStore } from 'redux';
const reducer = (state, action) => {
  if (action.type === 'up') {
    return { ...state, value: state+value + action.step };
  }
  return state;
};
const store = createStore(reducer, {value: 0});
export default store;
  • react-redux로 리액트와 리덕스 연결 필요

  • Provider는 Store를 전역적으로 사용할 수 있게 해줌
  • import { Provider } from "react-redux";
  • <Provider store={store}> store를 전역적으로 공급
    index.js
import store from "./Example/ExStore";
import { Provider } from "react-redux";
// 최상위에서 Provider로 컴포넌트들을 감싸줘야 함
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);
  • useSelector는 상태를 읽을 때 사용, useDispatch는 상태를 변경할 때 사용, reducer는 상태 변경을 처리하는 함수
  • import { useSelector, useDispatch } from "react-redux";
  • useSelector((state) => state.value); 값을 읽을 때 사용

  • npm install @reduxjs/toolkit redux toolkit 설치
  • 스토어를 분리해서 사용 -> slice
  • createSlice slice 생성
  • configureStore slice를 합친 store 생성 -> createStore 대체
import { configureStore } from "@reduxjs/toolkit";
import countUp from "./countUpSlice";
import countDown from "./countDownSlice";
const store = configureStore({
  reducer: {
    countUp: countUp.reducer,
    countDown: countDown.reducer
  }
});
export default store;
  • createAction 액션 생성 함수 생성
  • createReducer reducer 함수 생성
  • createSelector state 값 가져오기 -> useSelector 대체
  • Action의 payload는 내용이라는 뜻

- 220624

테스팅은 처음 학습해봤는 데 처음부터 끝까지 초면인지라 처음엔 감잡기가 힘들었는데 실습 문제를 몇번 풀어보니 대충 이런거구나 감을 잡을 수 있었다. 이번주에 배운 내용들은 전체적으로 어렵지만 하나도 버릴게 없고 중요한 내용들이었다. 힘들지만 얼마 안남았으니 파이팅해야겠다..!

  • 테스트 종류 3가지
    유닛(Unit) 테스트 : 프로젝트의 기능을 잘게잘게 쪼개서 테스트
    통합(Integrated) 테스트 : 기능단위로 묶어서 잘 작동하는지 테스트
    E2E(End-to-End) 테스트 : 프로젝트가 브라우저 위에서 잘 동작하는지 사용자 관점에서 테스트
  • 테스팅 용어
    Mocking : 특정 동작을 흉내 내는 것
    Stubbing : 더미를 채워 넣는 것
  • 테스팅 구성 3가지
    setup : 테스트를 위한 환경 생성
    expectation : 테스트를 위한 코드를 작성
    assertion : 테스트 결과가 원하는 대로 나왔는지를 검증

  • 리액트 테스팅 툴 - jest, react-testing-library

  • jest
    • Assertion Matchers : toBe() toEqual() toContain() toMatch() toThrow()
    • Async assertion : test() done()
    • Mock functions : jest.fn() jest.mock() mockReturnValueOnce() mockResolvedValue()
    • Mock functions assertion : toHaveBeenCalled toHaveBeenCalledWith toHaveBeenLastCalledWith
    • Lifecycle functions : beforeEach afterEach beforeAll afterAll
    • Grouping : describe() test()
    • Snapshot testing : toMatchSnapshot() toMatchInlineSnapshot()

  • react-testing-library
    Query - 렌더링 된 DOM 노드에 접근하여 엘리먼트를 가져오는 메서드
    get - 동기적으로 처리되며 타겟을 찾지 못할 시 에러를 던짐
    getBy-, getAllBy-
    find - 비동기적으로 처리되며 타겟을 찾지 못할 시 에러를 던짐
    findBy-, findAllBy-
    query - 동기적으로 처리되며 타겟을 찾지 못할 시 null을 반환
    queryBy-, queryAllBy-
    • dom 테스팅 - toBeInTheDocument(), toHaveValue(), toBeDisabled(), toBeVisible()
    ByRole ByText ByPlaceholderText ByLabelText ByDisplayValue ByAltText ByTitle, ByTestId
    이벤트 - userEvent, fireEvent, createEvent

0개의 댓글