Redux的设计思想很简单,就两句话。编程
* Web应用是一个状态机,视图与状态是一一对应的
* 全部的状态,保存在一个对象里面redux
Store:数组
Store就是保存数据的地方,你能够把它当作一个容器。整个应用只能有一个Store。服务器
Redux提供createStore这个函数,用来生成Store。dom
import { createStore } from 'redux';
const store = createStore(fn);
上面代码中,createStore函数接受里呢一个函数做为参数,返回新生成的Store对象。函数式编程
State:函数
Store对象包含全部数据。若是想获得某一时点的数据,就要对Store生成快照。这种时点的数据集合,就叫作State。spa
当前时刻的State,能够经过store.getState()拿到设计
import { createStore } from 'redux'; const store = createStore(fn); const state = store.getState();
Redux规定,一个State对应一个View。只要State相同,View就相同。你知道State,就知道View是什么样,反之亦然。code
Action:
State的变化,会致使View的变化。可是,用户接触不到State,只能接触到View。因此,State的变化时View致使的。Action就是View发出的通知,表示State应该要发生变化了。
Action是一个对象。其中的type属性是必须的,表示Action的名称。其余属性能够自由设置。
const action = { type:'ADD_TODO', payloadL:'Learn Redux' };
上面代码中,Action的名称是ADD_TODO,它携带的额信息是字符串Learn Redux。
能够这样理解,Action描述当前发生的事情。改变State的惟一方法,就是使用Action。他会运送数据到Store。
ActionCreator:
View要发送多少种消息,就会有多少种Action。若是都手写,会很麻烦。能够定义一个函数来生成Action,这个函数就叫ActionCreator。
const ADD_TODO = '添加 TODO'; function addToDo(text){ return { type:ADD_ToDo, text } } const action = addToDo('Learn Redux');
上面代码中,addToDo函数就是一个ActionCreator。
store.dispatch():
store.dispatch()是View发出Action的惟一方法
import { createStore } from 'redux'; const store = createStore(fn); store.dispatch({ type:'ADD_TODO', payload:'Learn Redux' });
上面代码中,store.dispatch接受一个Action对象做为参数,将它发送出去。
结合ActionCreator,这段代码能够改写以下。
store.dispatch(addTodo('Learn Redux'));
Reducer:
Store收到Action之后,必须给出一个新的State,这样View才会发生变化。这种State的计算过程就叫作Reducer。
Reducer是一个纯函数,它接受Action和当前State做为参数,返回一个新的State。
const reducer = function(state,action){ //... return new_state; }
整个应用的初始状态,能够做为State的默认值。下面是一个实际的例子。
const defaultState = 0; const reducer = (state = defaultState,action) = >{ switch(action.type){ case "ADD": return state += action.payload; default: return state; } }; const state = reducer(1,{ type:'ADD', payload:2 });
上面代码中,reducer函数收到名为ADD的Action之后,就返回一个新的State,做为加法的计算结果。其余运算的逻辑(好比剪发),也能够根据Action的不一样来实现。
实际应用中,Reducer函数不一样像上面这样手动调用,store.dispatch方法会触发reducer的自动执行。为此,Store须要知道Reducer函数,作法就是在生成Store的视乎,将Reducer传入createStore方法。
import { createStore } from 'redux';
const store = createStore(reducer);
上面代码中,createStore接受Reducer做为参数,生成一个新的Store。之后每当store.dispatch发送过来一个新的Action,就会自动调用Reducer,获得新的State。
为何这个函数叫作Reducer呢?由于它能够做为数组的reducer方法的参数。请看下面的例子,一系列Action对象按照顺序做为一个数组。
const actions = [ {type:'ADD',payload:0}, {type:'ADD',payload:1}, {type:'ADD',payload:2} ]; const total = actions.reducer(reducer,0);//3
上面代码中,数组actions表示依次有三个Action,分别是假0、加1和加2.数组的reducer方法接受Reducer函数做为参数,就能够直接获得最终的状态3。
纯函数:
Reducer函数最重要的特征是,它是一个纯函数。也就是说,只要是一样的输入,必须获得一样的输出。
纯函数是函数式编程的概念,必须遵照如下一些约束。
* 不得改写参数
* 不能调用系统I/O的API
* 不能调用Date.now()或者Math.random()等不纯的方法,由于每次会获得不同的结果。
因为Reducer是纯函数,就能够保证一样的State,一定获得一样的View。但也正由于这一点,Reducer函数里面不能改变State,必须返回一个全新的对象,请参考下面的写法。
//State是一个对象 function reducer(state,action){ return Object.assign({},state,{ thingToChange }); //或者 return { ...state,...newState }; } //State是一个数组 function reducer(state,action){ return [...state,newItem]; }
最好把State对象设成只读。你无法改变它,要获得新的State,惟一办法就是生成一个新对象。这样的好处是,任什么时候候,与某个View对应的State老是一个不变的对象。
store.subscribe():
Store容许使用store.subscribe方法设置监听函数,一旦State发生变化,就自动执行这个函数。
import { createStore } from 'redux'; const store = createStore(reducer); store.subscribe(listener);
显然,只要把View的更新函数(对于React项目,就是组件的render方法或setState方法)放入listen,就会实现View的自动渲染。
store.subscribe方法返回一个函数,调用这个函数就能够解除监听。
let unsunscribe = store.subscribe(()=>
console.log(store.getState())
);
unsubscribe();
Store的实现:
上一节介绍了Redux涉及的基础概念,能够发现Store提供了三个方法。
* store.getState()
* store.dispatch()
* store.subscribe()
import { createStore } from 'redux';
let { subscribe,dispatch,getState } = createStore(reducer);
createStore方法还能够接受第二个参数,表示State的最初状态。这一般是服务器给出的。
let store = createStore(todoApp,window.START_FORM_SERVER)
上面的代码中,window.START_FORM_SERVER就是整个应用的状态初始值。注意,若是提供了这个参数,他会覆盖Reducer函数的默认初始值。
下面是createStore方法的一个简单实现,能够了解一下 Store 是怎么生成的。
const createStore = (reducer) => { let state; let listeners = []; const getState = () => state; const dispatch = (action) => { state = reducer(state, action); listeners.forEach(listener => listener()); }; const subscribe = (listener) => { listeners.push(listener); return () => { listeners = listeners.filter(l => l !== listener); } }; dispatch({}); return { getState, dispatch, subscribe }; };
Reducer 的拆分:
Reducer 函数负责生成 State。因为整个应用只有一个 State 对象,包含全部数据,对于大型应用来讲,这个 State 必然十分庞大,致使 Reducer 函数也十分庞大。
const chatReducer = (state = defaultState, action = {}) => { const { type, payload } = action; switch (type) { case ADD_CHAT: return Object.assign({}, state, { chatLog: state.chatLog.concat(payload) }); case CHANGE_STATUS: return Object.assign({}, state, { statusMessage: payload }); case CHANGE_USERNAME: return Object.assign({}, state, { userName: payload }); default: return state; } };
上面代码中,三种 Action 分别改变 State 的三个属性。
* ADD_CHAT:chatLog属性
* CHANGE_STATUS:statusMessage属性
* CHANGE_USERNAME:userName属性
这三个属性之间没有联系,这提示咱们能够把 Reducer 函数拆分。不一样的函数负责处理不一样属性,最终把它们合并成一个大的 Reducer 便可。
const chatReducer = (state = defaultState, action = {}) => { return { chatLog: chatLog(state.chatLog, action), statusMessage: statusMessage(state.statusMessage, action), userName: userName(state.userName, action) } };
上面代码中,Reducer 函数被拆成了三个小函数,每个负责生成对应的属性。
这样一拆,Reducer 就易读易写多了。并且,这种拆分与 React 应用的结构相吻合:一个 React 根组件由不少子组件构成。这就是说,子组件与子 Reducer 彻底能够对应。
Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,而后用这个方法,将它们合成一个大的 Reducer。
import { combineReducers } from 'redux'; const chatReducer = combineReducers({ chatLog, statusMessage, userName })
export default todoApp;
上面的代码经过combineReducers方法将三个子 Reducer 合并成一个大的函数。
这种写法有一个前提,就是 State 的属性名必须与子 Reducer 同名。若是不一样名,就要采用下面的写法。
const reducer = combineReducers({ a: doSomethingWithA, b: processB, c: c }) // 等同于 function reducer(state = {}, action) { return { a: doSomethingWithA(state.a, action), b: processB(state.b, action), c: c(state.c, action) } }
总之,combineReducers()作的就是产生一个总体的 Reducer 函数。该函数根据 State 的 key 去执行相应的子 Reducer,并将返回结果合并成一个大的 State 对象。
下面是combineReducer的简单实现。
const combineReducers = reducers => { return (state = {}, action) => { return Object.keys(reducers).reduce( (nextState, key) => { nextState[key] = reducers[key](state[key], action); return nextState; }, {} ); }; };
你能够把全部子 Reducer 放在一个文件里面,而后统一引入。
import { combineReducers } from 'redux' import * as reducers from './reducers' const reducer = combineReducers(reducers)
用本身的话来阐述:
1. 首先建立store, 2. 而后编写reducer,返回状态,在reducer里面设置默认状态 3. 在组件中引入store,把状态挂载在组件的state中, 4. 在TYPES中建立变量, 5. 在actions中写方法,传入reducer中, 6. 把方法写在ActionCreators中,而后把方法引入actions中, 7. 在actions中利用store.dispatch(action)把action传入到reducer中, 8. 在Reducer中,使用switch来判断action.type, 9. 把actions引入到组件中,调用actions里面的方法, 10. 要想数据改变,须要在组件中更新一下。