redux

1. 前言

redux 基本思想是保证数据的单向流动,同时便于控制、使用、测试。

2. 主干逻辑介绍(createStore)

demo

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
// 首先定义一个改变数据的plain函数,成为reducer
function count (state, action) {
    var defaultState = {
        year: 2015,
      };
    state = state || defaultState;
    switch (action.type) {
        case 'add':
            return {
                year: state.year + 1
            };
        case 'sub':
            return {
                year: state.year - 1
            }
        default :
            return state;
    }
}
 
// store的创建
var createStore = require('redux').createStore;
var store = createStore(count);
 
// store里面的数据发生改变时,触发的回调函数
store.subscribe(function () {
      console.log('the year is: ', store.getState().year);
});
 
// action: 触发state改变的唯一方法(按照redux的设计思路)
var action1 = { type: 'add' };
var action2 = { type: 'add' };
var action3 = { type: 'sub' };
 
// 改变store里面的方法
store.dispatch(action1); // 'the year is: 2016
store.dispatch(action2); // 'the year is: 2017
store.dispatch(action3); // 'the year is: 2016

.

 

posted @   每天都要进步一点点  阅读(139)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示