Redux

류슬기·2021년 4월 20일
0

TIL

목록 보기
12/16
post-thumbnail

https://redux.js.org 참고
Redux Toolkit을 사용하지 않은 Vanila Redux로 일단 개념 잡기

Redux를 사용하는 이유

함수형 프로그램밍을 해야 하는데 리액트는 클로저함수 구조
그래서 pure함수인 리덕스가 필요

리턴의 형태가 (...)

const test = () => {
	return(<></>)
}

리듀서는 function object 순수함수 구조
순수함수는 외부(리액트)의 상태를 변경하지 않으면서 동일한 인자에 대해 항상 똑같은 값을 리턴
리턴의 형태{...}

const todoApp = (state = {}, action) =>{
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  }
}

Flux Pattern

Flux는 MVC와 다르게 단방향으로 데이터가 흐른다
action -> dispatch -> store <-> view

Redux

A Predictable State Container for JS Apps

리덕스는 상태 컨테이너다.

global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.

  • 스토어는 1개
  • 트리 안에 객체가 있는데 그 객체는 상태
  • 트리구조 ⇒ 그래프구조(노드+엣지)
    • 반드시 Root 를 가진다(리액트는 컴포넌트 트리구조, 리덕스는 리듀서 트리구조)
// 상태 객체(트리)구조
{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}
  • 상태트리(=객체트리)를 변경하는 유일한 방법은 액션객체를 parameter로 전달하는 것
  • 상태를 바꾸기 위해서는 바로 변경해서는 안되고 액션을 통해 상태 변경을 정의
  • reducer를 통해 변경이 작성

=> 상태, 액션은 객체, 전체 상태를 변경하기 위해서 reducer 함수를 사용하는데 이때 상태를 변경하는 것은 액션이다.

To change something in the state, you need to dispatch an action

디스패치 = 준비 상태에서 실행 상태로 바뀌는 것
dispatch (processname) : ready → running

store

객체
상태컨테이너
store 안에는 state, action, reducer가 있다.
Singleton Pattern

state

스토어 안에 있는 객체
global state

action

reducer를 호출하는 객체
상태를 바꾸는 것 type이라는 key가 있다. ⇒ state key가 된다.

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

action이 호출 될 때 마다 해당하는 상태를 변경하는 것 => Decoration Pattern

reducer

스테이트를 변경하는 함수

not mutate the state object, but return a new object if the state changes

(state, action) ⇒ 변경된state

handleActions()

action의 type에 따라 작업

useDispatch()

const dispatch = useDispatch();

const onIncrease = useCallback(() => {
  dispatch(increase());
}, [dispatch]);

리덕스에서 만들어 둔 액션들 중에서 리액트가 골라서 디스패치에 담아서 리덕스로 보낸다.
디스패치는 프로세스 상태를 ready에서 running으로 바꾸는 것
onIncrease 이벤트가 발생하면 스토어에서 선언되었던 increase 메소드를 호출

useSelector()

store의 state를 리스너(=구독)하는 메소드

const number = useSelector(state => state.counterReducer.number);

의문점이 있었는데 해결

const number = useSelector((state) => {
       console.log(state);
});

이렇게 콘솔 찍어보면 counterReducer가 출력된다.

그렇다면 counterReducer 메소드 내부의 state를 참조 할 수 있다는 건데 useSelector에 state.counterReducer라고 리턴을 정의해주지 않았는데? 어떻게?

const counterReducer = handleActions({...});

react-redux 참고
useSelector() will also subscribe to the Redux store, and run your selector whenever an action is dispatched.

현재 내가 작성한 store에

export default counterReducer;

로 하였고, useSelector()의 state parameter는 store를 말하기 때문이다.

profile
FE Developer🌱

0개의 댓글