redux

The Single Immutable State Tree

Describing State Changes with Actions

Pure and Impure Functions

The Reducer Function

Reducer function: (the function has to be pure function—>get an object, do somrthing, return new object)

  • takes the previous state of the app
  • the actions being dispatched
  • returns the next state of the app.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//A reducer function takes state and action
funciton counter = (state = 0, action) => {
switch (action.type){
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}

const {createStore} = Redux;
const store = createStore(counter);

const render = () => {
document.body.innerText = store.getState();
};

//render something to the body with subscribe
store.subscribe(render);
render();

document.addEventListener('click', () => {
//dispatch an action
store.dispatch({type: 'INCREMENT'});
})

/*=========================Unit Test=============================*/
//Test using expect by assertion断言库
expect(
counter(0, {type: 'INCREMENT'})
).toEqual(1);

expect(
counter(1, {type: 'INCREMENT'})
).toEqual(2);

expect(
counter(2, {type: 'INCREMENT'})
).toEqual(3);