-
이제 버튼에 연결해서 기능을 만들어보면
const add = document.getElementById('add'); const minus = document.getElementById('minus'); const number = document.getElementById('number'); const countModifier = (count = 0, action) => { if (action.type === "ADD") { return count + 1; } else if (action.type === "MINUS") { return count - 1; } else { return count; } } const countStore = createStore(countModifier);
const handleAdd = () => { countStore.dispatch({ type: "ADD" }) } const handleMinus = () => { countStore.dispatch({ type: "MINUS" }) } add.addEventListener('click',handleAdd); minus.addEventListener('click',handleMinus);
이렇게, 함수를 만들어서 이벤트리스너에 넣어주면 된다. 함수를 만들어서 넣는게 아니라면 () => {count~~} 이렇게 Arrow function으로 넣어줄 수 있다.
이러면 기능을 잘 동작하지만, 화면에 나타나진 않는다.
이때, subscribe라는 store의 함수를 쓸 수 있다.
지금까진 dispatch, getState만 사용했다.
const onChange = () => { number.innerText = countStore.getState(); } countStore.subscribe(onChange);
이렇게 사용하면, countStore가 변화가 있을때마다, subscribe가 감지해서 onChange함수를 불러서 화면에 표시해줄 것이다.
'Redux' 카테고리의 다른 글
mapStateToProps와 mapDispatchToProps (0) 2022.07.28 리덕스만으로 todo 만들기 (0) 2022.07.27 개선사항 (0) 2022.07.27 action (0) 2022.07.27 store 와 reducer (0) 2022.07.27