Redux Basic

 

리덕스 개요

리덕스 Action

리덕스 Reducers

createStore, combineReducers

Context 로 연결하기

react-redux

Lead Software Engineer @ProtoPie

Microsoft MVP

TypeScript Korea User Group Organizer

Marktube (Youtube)

Mark Lee

이 웅재

Redux 개요

Component - Communication

Component - Communication - Redux

Redux

"(1) 단일 스토어를 만드는 법" 과,
"(2) 리액트에서 스토어 사용하는 법" 을 익히는 시간

  • 단일 스토어다!
     

  • [만들기] 단일 스토어 사용 준비하기

    • import redux

    • 액션을 정의하고,

    • 액션을 사용하는, 리듀서를 만들고,

    • 리듀서들을 합친다.

    • 최종 합쳐진 리듀서를 인자로, 단일 스토어를 만든다.
       

  • [사용하기] 준비한 스토어를 리액트 컴포넌트에서 사용하기

    • import react-redux

    • connect 함수를 이용해서 컴포넌트에 연결

npx create-react-app redux-start

cd redux-start

npm i redux

Action - 액션

리덕스의 액션이란 ?

  • 액션은 사실 그냥 객체 (object) 입니다.
     

  • 두 가지 형태의 액션이 있습니다.

    • { type: 'TEST' } // payload 없는 액션

    • { type: 'TEST', params: 'hello' } // payload 있는 액션
       

  • type 만이 필수 프로퍼티이며, type 은 문자열 입니다.

리덕스의 액션 생성자란 ?

  • 액션을 생성하는 함수를 "액션 생성자 (Action Creator)" 라고 합니다.

  • 함수를 통해 액션을 생성해서, 액션 객체를 리턴해줍니다.

  • createTest('hello'); // { type: 'TEST', params: 'hello' } 리턴

function 액션생성자(...args) { return 액션; }

리덕스의 액션은 어떤 일을 하나요 ?

  • 액션 생성자를 통해 액션을 만들어 냅니다.

  • 만들어낸 액션 객체를 리덕스 스토어에 보냅니다.

  • 리덕스 스토어가 액션 객체를 받으면 스토어의 상태 값이 변경 됩니다. 

  • 변경된 상태 값에 의해 상태를 이용하고 있는 컴포넌트가 변경됩니다.

  • 액션은 스토어에 보내는 일종의 인풋이라 생각할 수 있습니다.

액션을 준비하기 위해서는 ?

  • 액션의 타입을 정의하여 변수로 빼는 단계

    • 강제는 아닙니다. (그러므로 안해도 됩니다.)

    • 그냥 타입을 문자열로 넣기에는 실수를 유발할 가능성이 큽니다.

    • 미리 정의한 변수를 사용하면, 스펠링에 주의를 덜 기울여도 됩니다.
       

  • 액션 객체를 만들어 내는 함수를 만드는 단계

    • 하나의 액션 객체를 만들기 위해 하나의 함수를 만들어냅니다.

    • 액션의 타입은 미리 정의한 타입 변수로 부터 가져와서 사용합니다.

액션 준비 코드

// actions.js

// 액션의 type 정의
// 액션의 타입 => 액션 생성자 이름
// ADD_TODO => addTodo
export const ADD_TODO = 'ADD_TODO';

// 액션 생산자
// 액션의 타입은 미리 정의한 타입으로 부터 가져와서 사용하며,
// 사용자가 인자로 주지 않습니다.
export function addTodo(text) {
  return { type: ADD_TODO, text }; // { type: ADD_TODO, text: text }
}

Reducers - 리듀서

  • 액션을 주면, 그 액션이 적용되어 달라진(안달라질수도...) 결과를 만들어 줌.
     

  • 그냥 함수입니다.

    • Pure Function

    • Immutable

      • 왜용 ?

        • 리듀서를 통해 스테이트가 달라졌음을 리덕스가 인지하는 방식

리덕스의 리듀서란 ?

  • 액션을 받아서 스테이트를 리턴하는 구조

  • 인자로 들어오는 previousState 와 리턴되는 newState 는
    다른 참조를 가지도록 해야합니다.

리덕스의 리듀서란 ?

function 리듀서(previousState, action) { 
  return newState;
}​

리듀서 함수 만들기

// reducers.js
import { ADD_TODO } from './actions';

export function todoApp(previousState, action) {
  if (previousState === undefined) {
    return [];
  }
  if (action.type === ADD_TODO) {
    return [...previousState, { text: action.text }];
  }
  return previousState;
}

createStore

redux 로 부터 import

스토어를 만드는 함수

  • createStore<S>(
      reducer: Reducer<S>,
      preloadedState: S,
      enhancer?: StoreEnhancer<S>
    ): Store<S>;

const store = createStore(리듀서);
// store.js
import { todoApp } from './reducers';
import { createStore } from 'redux';
import { addTodo } from './actions';

const store = createStore(todoApp);
console.log(store);

console.log(store.getState());

setTimeout(() => {
  store.dispatch(addTodo('hello'));
}, 1000);

export default store;

스토어 만들기

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import store from './store';

store.subscribe(() => {
  const state = store.getState();

  console.log('store changed', state);
});

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

store

  • store.getState();
     

  • store.dispatch(액션);, store.dispatch(액션생성자());
     

  • const unsubscribe = store.subscribe(() => {});

    • 리턴이 unsubscribe 라는 점 !

    • unsubscribe(); 하면 제거
       

  • store.replaceReducer(다른리듀서);

로직을 추가하기

action 을 정의하고, action 생성자를 만들고, reducer 를 수정

action 을 정의하고,

// actions.js

// 액션의 type 정의
// 액션의 타입 => 액션 생성자 이름
// ADD_TODO => addTodo
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';

// 액션 생산자
// 액션의 타입은 미리 정의한 타입으로 부터 가져와서 사용하며,
// 사용자가 인자로 주지 않습니다.
export function addTodo(text) {
  return { type: ADD_TODO, text }; // { type: ADD_TODO, text: text }
}

action 생성자를 만들고,

// actions.js

// 액션의 type 정의
// 액션의 타입 => 액션 생성자 이름
// ADD_TODO => addTodo
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';

// 액션 생산자
// 액션의 타입은 미리 정의한 타입으로 부터 가져와서 사용하며,
// 사용자가 인자로 주지 않습니다.
export function addTodo(text) {
  return { type: ADD_TODO, text }; // { type: ADD_TODO, text: text }
}

export function completeTodo(index) {
  return { type: COMPLETE_TODO, index }; // { type: COMPLETE_TODO, index: index}
}

reducer 를 수정

import { ADD_TODO, COMPLETE_TODO } from './actions';

export function todoApp(previousState, action) {
  if (previousState === undefined) {
    return [];
  }
  if (action.type === ADD_TODO) {
    return [...previousState, { text: action.text, completed: false }];
  }
  if (action.type === COMPLETE_TODO) {
    const newState = [];
    for (let i = 0; i < previousState.length; i++) {
      newState.push(
        i === action.index
          ? { ...previousState[i], completed: true }
          : { ...previousState[i] },
      );
    }
    return newState;
  }
  return previousState;
}

dispatch

// store.js
import { todoApp } from './reducers';
import { createStore } from 'redux';
import { addTodo, completeTodo } from './actions';

const store = createStore(todoApp);
console.log(store);

console.log(store.getState());

setTimeout(() => {
  store.dispatch(addTodo('hello'));
  setTimeout(() => {
    store.dispatch(completeTodo(0));
  }, 1000);
}, 1000);

export default store;

애플리케이션이 커지면, state 가 복잡해진다.

  • 리듀서를 크게 만들고, state 를 변경하는 모든 로직을 담을 수도 있습니다.

  • 리듀서를 분할해서 만들고, 합치는 방법을 사용할 수 있습니다.

    • todos 만 변경하는 액션들을 처리하는 A 라는 리듀서 함수를 만들고,

    • filter 만을  변경하는 액션들을 처리하는 B 라는 리듀서 함수를 만들고,

    • A 와 B 를 합침.

[
  {
    text: 'Hello',
    completed: false
  }
]
{
  todos: [
    {
      text: 'Hello',
      completed: false
    }
  ],
  filter: 'SHOW_ALL'
}

한번에 다하는 리듀서

import { ADD_TODO, COMPLETE_TODO } from './actions';

export function todoApp(previousState, action) {
  if (previousState === undefined) {
    return { todos: [], filter: 'SHOW_ALL' };
  }
  if (action.type === ADD_TODO) {
    return {
      todos: [...previousState.todos, { text: action.text, completed: false }],
      filter: previousState.filter,
    };
  }
  if (action.type === COMPLETE_TODO) {
    const todos = [];
    for (let i = 0; i < previousState.todos.length; i++) {
      todos.push(
        i === action.index
          ? { ...previousState.todos[i], completed: true }
          : { ...previousState.todos[i] },
      );
    }
    return { todos, filter: previousState.filter };
  }
  return previousState;
}

리듀서 분리

export function todos(previousState, action) {
  if (previousState === undefined) {
    return [];
  }
  if (action.type === ADD_TODO) {
    return [...previousState.todos, { text: action.text, completed: false }];
  }
  if (action.type === COMPLETE_TODO) {
    const newState = [];
    for (let i = 0; i < previousState.length; i++) {
      newState.push(
        i === action.index
          ? { ...previousState[i], completed: true }
          : { ...previousState[i] },
      );
    }
    return newState;
  }
  return previousState;
}

export function filter(previousState, action) {
  if (previousState === undefined) {
    return 'SHOW_ALL';
  }
  return previousState;
}

리듀서 합치기

export function todoApp(previousState = {}, action) {
  return {
    todos: todos(previousState.todos, action),
    filter: filter(previousState.filter, action),
  };
}

combineReducers

리덕스에서 제공하는 combineReducers 사용

import { combineReducers } from 'redux';

const todoApp = combineReducers({
  todos,
  filter,
});

Redux 를 React 에 연결

react-redux 안쓰고 연결하기

단일 store 를 만들고,

subscribe 와 getState 를 이용하여,
변경되는 state 데이터를 얻어,

props 로 계속 아래로 전달

  • componentDidMount - subscribe

  • componentWillUnmount - unsubscribe

// App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import { addTodo } from './actions';

function App({ store }) {
  const [state, setState] = useState(store.getState());
  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setState(store.getState());
    });
    return () => {
      unsubscribe();
    };
  });
  return (
    <div className="App">
      <header className="App-header">
        <p>{JSON.stringify(state)}</p>
        <button
          onClick={() => {
            store.dispatch(addTodo('Hello'));
          }}
        >
          추가
        </button>
      </header>
    </div>
  );
}

export default App;

Context API

useContext

import React from 'react';

const ReduxContext = React.createContext();

export default ReduxContext;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App2';
import * as serviceWorker from './serviceWorker';
import store from './store';
import ReduxContext from './context';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
import React, { useContext } from 'react';
import './App.css';
import { addTodo } from './actions';
import ReduxContext from './context';
import Button from './Button';

class App extends React.Component {
  static contextType = ReduxContext;
  _unsubscribe;
  state = this.context.getState();
  componentDidMount() {
    this._unsubscribe = this.context.subscribe(() => {
      this.setState(this.context.getState());
    });
  }
  componentWillUnmount() {
    this._unsubscribe();
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <p>{JSON.stringify(this.state)}</p>
          <Button />
        </header>
      </div>
    );
  }
}

export default App;
import React, { useContext } from 'react';
import { addTodo } from './actions';
import ReduxContext from './context';

export default function Button() {
  const store = useContext(ReduxContext);
  return (
    <button
      onClick={() => {
        store.dispatch(addTodo('Hello'));
      }}
    >
      추가
    </button>
  );
}

Redux 를 React 에 연결

react-redux 쓰고 연결하기

react-redux

  • Provider 컴포넌트를 제공해줍니다.

  • connect 함수를 통해 "컨테이너"를 만들어줍니다.

    • 컨테이너는 스토어의 statedispatch(액션) 를 연결한 컴포넌트에 props 로 넣어주는 역할을 합니다.​

    • 그렇다면 필요한 것은 ?

      • 어떤 state 를 어떤 props 에 연결할 것인지에 대한 정의

      • 어떤 dispatch(액션) 을 어떤 props 에 연결할 것인지에 대한 정의

      • 그 props 를 보낼 컴포넌트를 정의

npm i react-redux

Provider Component from react-redux

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App3';
import * as serviceWorker from './serviceWorker';
import store from './store';
import { Provider } from 'react-redux';

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

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Consumer from react-redux

import React, { useContext, useEffect, useState } from 'react';
import { ReactReduxContext } from 'react-redux';
import './App.css';
import { addTodo } from './actions';
import Button from './Button';

class App extends React.Component {
  render() {
    console.log(this.props);
    return (
      <div className="App">
        <header className="App-header">
          <p>{JSON.stringify(this.props.todos)}</p>
          <Button add={this.props.add} />
        </header>
      </div>
    );
  }
}
function AppContainer(props) {
  const { store } = useContext(ReactReduxContext);
  const [state, setState] = useState(store.getState());
  function add(text, dispatch) {
    console.log(text, dispatch);
    dispatch(addTodo(text));
  }
  useEffect(() => {
    const _unsubscribe = store.subscribe(() => {
      setState(store.getState());
    });
    return () => {
      _unsubscribe();
    };
  });
  return (
    <App
      {...props}
      todos={state.todos}
      add={text => add(text, store.dispatch)}
    />
  );
}

export default AppContainer;
import React from 'react';

export default function Button({ add }) {
  return <button onClick={() => add('hello')}>추가</button>;
}

connect function from react-redux

import React from 'react';
import './App.css';
import { addTodo } from './actions';
import { connect } from 'react-redux';
import Button from './Button';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <p>{JSON.stringify(this.props.todos)}</p>
          <Button add={this.props.add} />
        </header>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return { todos: state.todos };
};

const mapDispatchToProps = dispatch => {
  return {
    add: text => {
      dispatch(addTodo(text));
    },
  };
};

const AppContainer = connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);

export default AppContainer;
import React from 'react';

export default function Button({ add }) {
  return <button onClick={() => add('hello')}>추가</button>;
}

mapStateToProps, mapDispatchToProps

const mapStateToProps = state => {
  return { todos: state.todos };
};

const mapDispatchToProps = dispatch => {
  return {
    add: text => {
      dispatch(addTodo(text));
    },
  };
};

8. Redux Basic

By Woongjae Lee

8. Redux Basic

Fast Campus Frontend Developer School 17th

  • 1,082