Redux란 ?

GonnabeAlright·2021년 12월 12일
0
post-thumbnail

Redux란 ?

  • 애플리케이션 상태(State)를 용이하게 관리하기 위한 프레임 워크 (오픈 소스 JavaScript 라이브러리)

Action

  • 상태를 변경(state update)하기 위해 발생
{
  type: "EXAMPLE_TYPE",
  payload: amount
}

Action Creator

  • Action을 생성(반환)하는 함수
const withdrawMoney = (param) => {

  return {
    type: WITHDRAW_MONEY,
    payload: amount
  }
}

dispatch

  • Store의 내장 함수 중 하나
  • Reducer에게 어떤 action이 발생했는지 알리는 함수
  • dispatch(action) <=> dispatch(ActionCreator(param))

Store

  • 하나의 App에 단 하나의 Store만 존재
  • state, Reducer 및 기타 내장 함수 존재

    state

  • 데이터 및 UI 상태 등 어플리케이션을 유지하기 위한 정보
  • state의 변경 <=> View의 변경

Reducer

  • state에 변화를 일으키는 함수
  • Input: state, action
  • Output: state
export sampleReducer (state=initialState, action) {
  switch (action.type) {
    case WITHDRAW_MONEY:
      return {
        ...state,
         ammount: payload
       }
     default:
        return state;       
  }
}

Connect

  • React Native의 세계관과 Redux 세계관의 연결 함수
  • Store 내 state -> connect -> component 내 props
  • state 변경 -> 새로운 component 생성
  • Store가 가진 state를 어떻게 props에 엮을지 -> mapStateToProps
  • Reducer에 Action을 알리는 함수 dispatch을 어떻게 props에 엮을지 -> mapDispatchToProps
  • connect(mapStateToProps, mapDispatchToProps)(comment)

Redux의 3원칙

  • Single Source of Truth (신뢰 가능한 유일한 정보원)

    어플리케이션의 모든 state는 단일 store에서 관리

  • State in Read-Only (state는 읽기 전용)

    state의 변경은 반드시 action을 통해서

  • Changes are Made with Pure Functions

    (변경은 순수함수를 통해서만)
    Reducer는 순수함수로 정의
    인수변경 x, API 호출 x, 네트워크 요청 x, 순수함수가 아닌 함수(Date.now(), Math.random)의 호출 x

react-native run-ios 실행시 발생하는 에러

Failed to launch the app on simulator, An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405): Unable to lookup in current state: Shutdown

해결

  • 애플로고 클릭
  • 이 Mac에 관하여 - 저장공간 - 관리 - 개발자 - 프로젝트 빌드 데잍 및 인덱스 삭제 - 재부팅

Redux 셋업하기 (index.js)

import React from 'react';
import { AppRegistry } from 'react-native';
import App from './app/index';
import { name as appName } from './app.json';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import promiseMiddleware from 'redux-promise';
import reducers from './app/store/reducers';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPONSE__ || compose

const createStoreWithMiddleware = createStore(reducers, composeEnhancers(
  applyMiddleware(promiseMiddleware)
))

const appRedux = () => (
  <Provider store={createStoreWithMiddleware}>
    <App />
  </Provider>
)

AppRegistry.registerComponent(appName, () => appRedux);

createStore

  • store를 생성하기 위해 필요

applyMiddleware

  • middleware 사용

compose

  • 여러 store enhancers를 순차적으로 적용시키기 위한 함수형 프로그래밍 유틸리티

enhancer

  • store 인터페이스를 바꿔서 새로운 store 생성자로 바꾸는 고차함수

Provider

  • store를 react-native 컴포넌트로 패싱해주기 위해서 필요(store를 props로 받는 Provider로 최상위 컴포넌트를 감싸준다.)

promiseMiddleware

  • 비동기 처리가 필요한 action creator 사용을 위해서 필요

createStoreWithMiddleware

  • 리덕스 개발자 도구와 미들웨어를 동시 사용하기 위해서 필요

react-router-dom고 비슷한 역할을 하는 리액트 네비게이션

  • 자료구조의 스택처럼 하나씩 쌓아가는 개념. 만약 모바일 앱에서 어떤 다른 페이지로 이동을 한다고 했을 때 그 페이지로 완전히 전환 되는 것이 아닌
    페이지 위에 쌓인다고 할 수 있다.

eslint, prettier 설정하기

1. eslint 초기화

yarn/npx eslint --init
How would you like to use EsLint ?
- To check syntax, find problems, and enforce code style
What type of modules does your project use ?(Use arrow keys)
- JavaScript modules (import/export)
Which framework does your project use ? (Use arrow keys)
- React
Does your project use TypeScript ? (Y/N)
- N
Where does your code run ? (Press <space> to select, <a> to toggle all, <i> to invert selection)
- Node
How would you like to define a style for your project ? (Use arrow keys)
- Answer questions about your style
What format do you want your config file to be in ? (Use arrow keys)
- JavaScript
What style of indentation do you use ? (Use arrow keys)
- Spaces
What quotes do you use for strings ? (Use arrow keys)
- Single
What line endings do you use ? (Use arrow keys)
- Unix
Do you require semicolons? (Y/n)
- y

2. package.json 내용 추가

"scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ." // 추가하기 
  },

3. prettier 설치

yarn add --save-dev prettier eslint-plugin-prettier

4. eslint 설정 셋업

/* eslint-disable no-undef */
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
  ],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 13,
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks', 'prettier'],
  rules: {
    'prettier/prettier': ['error', { singleQuote: true, parser: 'flow' }],    // 싱글 따옴표 사용 (공식문서참고) https://github.com/prettier/eslint-plugin-prettier#options
    'linebreak-style': ['error', 'unix'],
    quotes: ['error', 'single', { avoidEscape: true }],
  },
};

5. prettier 설정 셋업

module.exports = {
  jsxBracketSameLine: true,
  trailingComma: 'all',
  arrowParens: "avoid",
  singleQuote: true,
  semi: true,
  bracketSpacing: true,
  useTabs: false,
  jsxSingleQuote: false,
  quoteProp: "as-needed",
  tabWidth: 2,
  printWidth: 80,
  endOfLine: "auto"
};

6. 실행 및 수정

yarn run lint // 실행
yarn eslint . --fix  // 모든 에러 수정

0개의 댓글