Upload
fernando-daciuk
View
830
Download
1
Embed Size (px)
Citation preview
Whyreducer?
var arr = [1, 2, 3];
var sum = arr.reduce(function(acc, item) {
return acc + item;
}, 0);
console.log(sum); // 6
Whyreducer?
var arr = [1, 2, 3];
var sum = arr.reduce(function(acc, item) {
return acc + item;
}, 0);
console.log(sum); // 6
reducer
var arr = [1, 2, 3];
var sum = arr.reduce(function(acc, item) {
return acc + item;
}, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
var sum = arr.reduce(function(acc, item) {
return acc + item;
}, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
const sum = arr.reduce(function(acc, item) {
return acc + item;
}, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
const sum = arr.reduce((acc, item) => {
return acc + item;
}, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
const sum = arr.reduce((acc, item) =>
acc + item
, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
const sum = arr.reduce((acc, item) => acc + item
, 0);
console.log(sum); // 6
Whyreducer?
const arr = [1, 2, 3];
const sum = arr.reduce((acc, item) => acc + item, 0);
console.log(sum); // 6
Whyreducer?
Anotherreducer example
const arr = [1, 2, 3];
const state = arr.reduce((acc, item) => {
return acc.concat(item + 1);
}, []);
console.log(state); // [2, 3, 4]
action ‘INCREMENT’ => plus 1
action ‘DECREMENT’ => minus 1
action ‘UNKNOWN’ => previous state
Creating acounter
action ‘INCREMENT’ => plus 1
action ‘DECREMENT’ => minus 1
action ‘UNKNOWN’ => previous state
state undefined => initial state (0)
Creating acounter
Creating acounter
counter.js
const counter = (state, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
}
}
Creating acounter
counter.js
const counter = (state, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
}
}
Creating acounter
counter.js
const counter = (state, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
}
return state;
}
Creating acounter
counter.js
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
}
return state;
}
storemethods
import { createStore } from 'redux';
import counter from './reducers/counter';
const store = createStore(counter);
console.log(store.getState()); // 0
storemethods
import { createStore } from 'redux';
import counter from './reducers/counter';
const store = createStore(counter);
console.log(store.getState()); // 0
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // 1
storemethodsimport { createStore } from 'redux';
import counter from './reducers/counter';
const store = createStore(counter);
store.subscribe(() => {
console.log(store.getState());
});
store.dispatch({ type: 'INCREMENT' }); // 1
store.dispatch({ type: 'INCREMENT' }); // 2
store.dispatch({ type: 'DECREMENT' }); // 1