이챙의 개발 log
Redux 작동 원리(action,dispatch,reducer,store) 이해하기 (with.react)
>>Redux
state를 관리하는 도구입니다
store라는 저장소에서 component들의 state를 관리하죠
component가 많아지고 관리해야하는 state들이 많아지면 props관리가 힘들어집니다.
redux를 사용하게 되면 모든 component에서 reducer함수와 action을 통해 state에 접근 할 수 있습니다.
그럼 어떻게 state를 관리할까요
바로 action을 dispatch하면 reducer함수를 호출합니다.
reducer는 store에가서 현재 state값을 가져와 새로운 state를 반환해줍니다.

action
//components import {TEST} from './redux' //action type 가져오기 dispatch({type:TEST}) dispatch({type:TEST,data:'test'})// data 추가
component에서 redux에서 관리하고 있는 state에 접근하기 위해
dipatch로 action을 객체로 전달합니다.
action 의 type 속성은 string이며 관리하기 쉽도록 상수로 변경하여 전달하는 것이 좋습니다.
type속성 뒤에는 data를 같이 전달할수 있습니다.
reducer 생성
//redux index.js export const TEST = 'TEST'; const rootReducer = (state=0,action){ switch(action.type){ case TEST return state+1 dafult: return state } }
action을 dispatch하면 reducer함수가 호출이 되는데요
dispatch로 전달된 action.type에 따라 실행할 코드를 작성하면
이전state에서 변경된 state를 확인하여
새로운 state를 반환해줍니다
store 생성
//redux index.js import {createStore} from 'redux'; export const TEST = 'TEST'; const rootReducer = (state=0,action){ switch(action.type){ case TEST return state+1 dafult: return state } } const store = redux.createStore( rootReducer );//store 생성 console.log(store.getState())//0 (현재 state 가져오기) store.dispath({type:TEST}) console.log(store.getState())//1
createStore로 store를 만들고
reducer에서 새로운 state값 반환하면
store에 저장되어있는 현재 state값이 업데이트됩니다.
store는 state를 관리해주고
getState() 메소드로 현재 state를 가져오며
dispatch를 통해 state를 업데이트 할수 있습니다
그리고 store가 변경이 되면 dispatch 가 store의 subscribe메소드를 통해
변경된 state 값으로 다시 render를 해주게 됩니다.
그러면 변경된 ui로 stater값이 바뀌겠죠
'redux' 카테고리의 다른 글
React 에 Redux 설치하기! (feat.왜 React에 Redux를 사용할까?) (0) | 2021.10.15 |
---|---|
Redux thunk 간단하게 알아보기 (3) | 2021.10.06 |
redux 불변성(immutable) (0) | 2021.06.01 |
이챙(leechaeng)
프론트엔드 개발도 하고 뛰기도 하고