첫 번째 React & Redux.

개시하다


공부했어redux.상당히 간단한 프로젝트였지만 그래도 해 봤어!
또한, 리액트를 사용한 성과물은 지금까지create-react-app 당신의 보살핌을 받아 왔고, 이번webpack에는 환경 구축이 진행되고 있습니다.그리고 webpack에 대해서도 공부를 하고 기사를 썼으면 좋겠다고 생각하고 있습니다.
github 공개 중이니 꼭 봐주세요.

프로젝트 개요


항목을'투표함'이라고 하는데 투표수를 추가 또는 삭감할 수 있고 개인 투표수와 전체 투표수도 확인할 수 있다.

파일 구성


├── src/
   ├── components/
           └──Counter.module.css  
	   └──Counter.tsx
   └──action.ts
   └──App.module.css
   └──App.tsx
   └──index.html
   └──index.tsx
   └──reducer.ts

최고급 index.tsx


import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { counterReducer, initialState } from './reducer';

const store = createStore(counterReducer, initialState);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root') as HTMLElement
);

Redux를 사용할 때 Provider라는 구성 요소로 앱 구성 요소를 props로 사용자에게 전달해야 한다.
store는createStore라는 함수로 만들어서 초기화해야 합니다.이 함수의 매개 변수는 Reducter와state의 초기 값을 제출해야 합니다.돌아봐, 리듀서.ts파일을 확인하는 과정에서 소개합니다.

store 상태 변경 동작


action.ts
export const ActionType = {
  DECREMENT: 'DECREMENT',
  INCREMENT: 'INCREMENT',
} as const;

type ValueOf<T> = T[keyof T];

export type Action = {
  type: ValueOf<typeof ActionType>;
  amount?: number;
};

export const decrement = (): Action => ({
  type: ActionType.DECREMENT,
});
export const increment = (): Action => ({
  type: ActionType.INCREMENT,
});
action의 역할은 이벤트 유형에 따라 구분된 대상을 만드는 것입니다.
이번에 필요한 활동은 증량과 체감의 종류이기 때문에 ActionType으로 정의합니다.
액션에서 만든 대상은 이벤트 유형의 속성 type과 덧붙일 수치를 저장하는 속성 amount가 필요하기 때문에 type Action에서 대상을 유형 정의합니다.
속성 type을 마우스 왼쪽 버튼으로 클릭하면 다음과 같은 증가 및 감소 유형이 됩니다.

그 다음은 액션.ts는 마지막으로 액션을 생성하는 함수를 정의했습니다.이 함수를 통해store의 상태를 바꿉니다.

새 상태의 Reducter 생성


reducer.ts
import { Reducer } from 'redux';
import { Action, ActionType as Type } from './action';

export type CounterState = {
  count: number;
};
export const initialState: CounterState = { count: 0 };

export const counterReducer: Reducer<CounterState, Action> = (
  state: CounterState = initialState,
  action: Action
): CounterState => {
  switch (action.type) {
    case Type.DECREMENT:
      return {
        ...state,
        count: state.count - 1,
      };
    case Type.INCREMENT:
      return {
        ...state,
        count: state.count + 1,
      };

    default:
      const check: never = action.type;//action.typeによるcase文の漏れを未然にチェック
      return state;
  }
};
reducter의 역할은 현재의 상태와 동작을 받아들여 새로운 상태를 창조하는 것이다.
우선, 상태의 유형과 상태의 초기 값을 각각 정의했다.
counter Reducter는 현재 상태와 동작을 변수에 분배하여 action이 정의한 이벤트 종류에 따라 새로운 상태를 되돌려주는 함수를 표시합니다.
아까 index.tsx에서createStore 함수 매개 변수에 대한 Reducter와state의 초기 값을 확인했습니다.
참고로 counter Reducter에서Generic형으로 정의된 Reducter에서 마우스 커서F12로 index를 눌러주세요.d.ts를 통해 유형 정의를 확인할 수 있습니다.index.d.ts

구성 요소에 Redux 기능 설치


App.tsx
import React from 'react';
import { useSelector } from 'react-redux';
import { CounterState } from './reducer';
import Counter from './components/Counter';
import AppCSS from './App.module.css';

type VoteManga = string[];

const App = () => {
  const count = useSelector<CounterState, number>((state) => state.count);
  const votesManga: VoteManga = ['Aさん', 'Bさん', 'Cさん'];

  return (
    <div className={AppCSS.container}>
      <div className={AppCSS.header}>
        <h1>投票箱</h1>
        <h2>Total Votes:{count}</h2>
      </div>
      {votesManga.map((vote, i) => (
        <Counter key={i} name={vote} />
      ))}
    </div>
  );
};

export default App;
count 변수의 정의Redux Hooks에서useSelector를 사용했습니다.useSelector에서 store 상태(state)를 가져올 수 있습니다.이곳에서는 전원 투표수를 확인하는 기능이 시행됐다.
이번에 Reducter가 정의한state의 종류는count뿐입니다. 대규모 프로젝트라면 이state의 종류는 매우 많습니다.useSlector를 통해 각 구성 요소에 필요한store의state라는 인상을 받지 않았을까요?
Counter.tsx
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { increment, decrement } from '../action';
import CounterCSS from './Counter.module.css';

interface Props {
  name: string;
}
const Counter: React.FC<Props> = ({ name }) => {
  const dispatch = useDispatch();
  const [votes, setVotes] = useState<number>(0);

  const handleDecrement = () => {
    dispatch(decrement());
    setVotes(votes - 1);
  };
  const handleIncrement = () => {
    dispatch(increment());
    setVotes(votes + 1);
  };

  return (
    <div className={CounterCSS.header}>
      <h2>{name}</h2>
      <h3>{`Votes: ${votes}`}</h3>
      <div>
        <button onClick={handleIncrement}>Increment</button>
        <button onClick={handleDecrement}>Decrement</button>
      </div>
    </div>
  );
};

export default Counter;
dispatch 변수 정의Redux Hooks의useDispatch를 사용합니다.이 디스패치 변수에 액션을 전달하면 이벤트별 액션이 복사됩니다.여기에는 개인 투표수를 확인, 추가, 삭감하는 기능이 시행됐다.
이상입니다.여기까지 읽어주셔서 감사합니다!!

좋은 웹페이지 즐겨찾기