January 15, 2020
const INCREASE = 'counter/INCREASE'
const DECREASE = 'counter/DECREASE'
export const increase = () => ({ type: INCREASE })
export const decrease = () => ({ type: DECREASE })
const initialState = {
number: 0,
}
function counter(state = initialState, action) {
switch (action.type) {
case INCREASE:
return {
number: state.number + 1,
}
case DECREASE:
return {
number: state.number - 1,
}
default:
return state
}
}
export default counter
import { combineReducers } from 'redux'
import counter from './counter'
import todos from './todos'
const rootReducer = combineReducers({
reducer1,
reducer2,
})
export default rootReducer
...
import { createStore } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./modules";
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
import React from 'react'
import Counter from '../components/Counter'
import { connect } from 'react-redux'
const CounterContainer = ({ number, increase, decrease }) => {
return <Counter number={number} onIncrease={increase} onDecrease={decrease} />
}
const mapStateToProps = state => ({
number: state.counter.number,
})
const mapDispatchToProsp = dispatch => ({
increase: () => {
console.log('increase')
},
decrease: () => {
console.log('decrease')
},
})
export default connect(mapStateToProps, mapDispatchToProsp)(CounterContainer)
mapStatetoProps는 리덕스 스토어 안의 상태를 컴포넌트의 props로 넘겨주기 위해 설정하는 함수이고, mapDispatchToProps는 액션 생성 함수를 컴포넌트의 props로 넘겨주기 위해 사용하는 함수이다. connect함수를 호출하고 나면 또 다른 함수를 반환하는데, 반환된 함수에 컴포넌트를 파라미터로 넣어 주면 리덕스와 연동된 컴포넌트가 만들어진다.