MENU
Combining Reducers
As each reducer is associated to only one state, combining reducers allows you to have 'multiple states' in the Redux store.
Notice a store can subscribe to multiple listeners, which will be invoked in the order they are subscribed every time an action is dispatched.
Below, we can also render both X and Y within one function.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html>
<html>
<head>
<title>Redux basic example</title>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
</head>
<body>
<div>
<p>
<span id="valueX">0</span> / <span id="valueY">2</span>
<button onclick="store.dispatch({ type: 'INCREMENT' })">+</button>
<button onclick="store.dispatch({ type: 'DECREMENT' })">-</button>
<button onclick="store.dispatch({ type: 'MUL', n:2 })">*2</button>
<button onclick="store.dispatch({ type: 'MUL', n:3 })">*3</button>
<button onclick="store.dispatch({ type: 'POW', n:2 })">^2</button>
<button onclick="store.dispatch({ type: 'POW', n:3 })">^3</button>
</p>
</div>
<script>
function counter(state=0, action) { // a reducer
if (typeof state === 'undefined') return 0;
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
}
function mfunc(state=2, action){ // another reducer
switch (action.type) {
case 'POW': return state ** action.n;
case 'MUL': return state * action.n;
default : return state;
}
}
var store = Redux.createStore(Redux.combineReducers({x:counter, y:mfunc}));
function renderX() {
document.getElementById('valueX').innerHTML = store.getState().x;
}
function renderY(){
document.getElementById('valueY').innerHTML = store.getState().y;
}
renderX(); store.subscribe(renderX);
renderY(); store.subscribe(renderY);
</script>
</body>
</html>
Note that you can use the ES6 shorthand syntax Redux.combineReducers({counter, mfunc}); which is equivalent to: Redux.combineReducers({counter:counter, mfunc:mfunc});