console.clear();
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
} // Create a store
const {createStore} = Redux;
// Store hold the state, can accept a reducer function
const store = createStore(counter); let currentState = store.getState();
console.log(currentState); // store.dispatch( {type: 'INCREMENT'} );
console.log(store.getState()); // store.subscribe( () => {
document.body.innerText = store.getState();
}); document.addEventListener('click', ()=>{
store.dispatch( {type: 'INCREMENT'} );
})
If we run we will miss the first init state, it starts from '2'...
So we need to call it before subscribe:
console.clear();
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
} // Create a store
const {createStore} = Redux;
// Store hold the state, can accept a reducer function
const store = createStore(counter); let currentState = store.getState();
console.log(currentState); // store.dispatch( {type: 'INCREMENT'} );
console.log(store.getState()); // const render = ()=> {
document.body.innerText = store.getState();
}
render();
store.subscribe( render); document.addEventListener('click', ()=>{
store.dispatch( {type: 'INCREMENT'} );
})