const initialState = {
counter:0,
text:'',
list:[]
};
위의 형식으로 스토어에 값들이 추가될 것 이다.
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';
const CHANGE_TEXT = 'CHANGE_TEXT';
const ADD_TO_LIST = 'ADD_TO_LIST';
정의 후 액션 함수에서 구현할 것이다.
const increase = () =>({
type:INCREASE,
})
const decrease = () =>({
type:DECREASE,
})
const changeText = (text) => ({
type:CHANTE_TEXT,
text,
})
const addToList = (item) => ({
type:ADD_TO_LIST,
item,
})
type은 필수로 정해줘야한다, 그 외의 값은 자유롭게 넣어줄 수 있다.
function reducer(state=initialState,action){
swtich(action.type){
case INCREASE:
return {...state, counter: state.counter+1}
case DECREASE:
return {...state, counter: state.counter-1}
case CHAGE_TEXT:
return {...state, text: action.text}
case ADD_TO_LIST:
return {...state, list: state.list.concat(action.item)}
default:
return state;
}
}
case에서 걸러지지 않은 타입들은,
기본(default)로 state를 리턴하도록 해둔다.
const store = createStore(reducer);
console.log(store.getState());
// 로그를 확인, 스토어 메서드들이 담긴걸 볼 수 있다.
// 이를통해 스토어가 정상 생성되었음이 확인되었다.
const listener = () =>{
const state = store.getState()
console.log(state)
}
//구독
const unsubscribe = store.subscribe(listener)
//구독 해제는 밑의 주석 해제
//unsubscribe()
store.dispatch(increase());
store.dispatch(decrease());
store.dispatch(changeText('hi~~~'));
store.dispatch(addToList({id:1,text:'oh yeah'})
-> npm start 후 콘솔을 확인,
정상 작동한다.
❗️ 구독을 해제해도 리듀서는 작동하지만 로그를 볼 수 없다.
아래는 practice.js의 전체 코드이다.
import { createStore } from 'redux';
const initialState = {
counter: 0,
text: '',
list: [],
};
// 액션타입을 정의
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';
const CHANGE_TEXT = 'CHANGE_TEXT';
const ADD_TO_LIST = 'ADD_TO_LIST';
//액션 생성함수
const increase = () => ({
type: INCREASE,
});
const decrease = () => ({
type: DECREASE,
});
const changeText = (text) => ({
type: CHANGE_TEXT,
text,
});
const addToList = (item) => ({
type: ADD_TO_LIST,
item,
});
//리듀서
function reducer(state = initialState, action) {
switch (action.type) {
case INCREASE:
return {
...state,
counter: state.counter + 1,
};
case DECREASE:
return {
...state,
counter: state.counter - 1,
};
case CHANGE_TEXT:
return { ...state, text: action.text };
case ADD_TO_LIST:
return { ...state, list: state.list.concat(action.item) };
default:
return state;
}
}
const store = createStore(reducer);
console.log(store.getState());
const listener = () => {
const state = store.getState();
console.log(state);
};
//구독
const unsubscribe = store.subscribe(listener);
//구독 해제
//unsubscribe();
store.dispatch(increase());
store.dispatch(decrease());
store.dispatch(changeText('hi~~~'));
store.dispatch(addToList({ id: 1, text: 'oh yeah' }));