Code States
Front-end boost camp
Today
I
Learned
🔮 벌써 50일?! 6월 22일 수업 시작 ~ 23일 연계!
▲ React 어플리케이션 예시
▲ Redux를 사용했을 때 데이터 흐름
// Reducer 연결하여 Store 생성
import { createStore } from 'redux';
const store = createStore(rootReducer);
// Reducer 예시
const count = 1
// Reducer를 생성할 때에는 초기 상태를 인자로 요구합니다.
const counterReducer = (state = count, action) => {
// Action 객체의 type 값에 따라 분기하는 switch 조건문입니다.
switch (action.type) {
//action === 'INCREASE'일 경우
case 'INCREASE':
return state + 1
// action === 'DECREASE'일 경우
case 'DECREASE':
return state - 1
// action === 'SET_NUMBER'일 경우
case 'SET_NUMBER':
return action.payload
// 해당 되는 경우가 없을 땐 기존 상태를 그대로 리턴
default:
return state;
}
}
// Reducer가 리턴하는 값이 새로운 상태가 됩니다.
// payload가 필요 없는 경우
{ type: 'INCREASE' }
// payload가 필요한 경우
{ type: 'SET_NUMBER', payload: 5 }
-- 보통 Action을 직접 작성하기보다는 Action 객체를 생성하는 함수를 만들어 사용 -> 액션 생성자(Action Creator)
// payload가 필요 없는 경우
const increase = () => {
return {
type: 'INCREASE'
}
}
// payload가 필요한 경우
const setNumber = (num) => {
return {
type: 'SET_NUMBER',
payload: num
}
}
// Action 객체를 직접 작성하는 경우
dispatch( { type: 'INCREASE' } );
dispatch( { type: 'SET_NUMBER', payload: 5 } );
// 액션 생성자(Action Creator)를 사용하는 경우
dispatch( increase() );
dispatch( setNumber(5) );
// useDispatch() : Action 객체를 Reducer로 전달해주는 Dispatch 함수를 반환하는 메서드
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()
dispatch( increase() )
console.log(counter) // 2
dispatch( setNumber(5) )
console.log(counter) // 5
// useSelector() : 컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드
// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러옵니다.
import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1
페어분 따라 코드를 쳐서 완성하긴 했는데... 미완성이라 복습이 더 필요하다. 이해 후 코드 정리 예정