redux学习笔记概括

设计思想:

(1)Web 应用是一个状态机,视图与状态是一一对应的。 json

(2)全部的状态,保存在一个对象里面。redux


核心源码:
数组



基本概念: promise

1.Store:就是保存数据的地方,你能够把它当作一个容器。整个应用只能有一个 Store。 bash

const store = createStore(fn); 复制代码

2.State:Store对象包含全部数据。若是想获得某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫作 State。 app

store.getState();复制代码

3.Action:State 的变化,会致使 View 的变化。可是,用户接触不到 State,只能接触到 View。因此,State 的变化必须是 View 致使的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。 异步

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
} 复制代码

4.store.dispatch():是 View 发出 Action 的惟一方法。  函数

5.Reducer:Store 收到 Action 之后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫作 Reducer。 post

const reducer = function (state, action) {
  // ...
  return new_state;
}; 复制代码

实际应用中,Reducer 函数不用像上面这样手动调用,store.dispatch方法会触发 Reducer 的自动执行。为此,Store 须要知道 Reducer 函数,作法就是在生成 Store 的时候,将 Reducer 传入createStore方法。 为何这个函数叫作 Reducer 呢?由于它能够做为数组的reduce方法的参数。fetch

array.reduce(function(total, currentValue, currentIndex, arr), initialValue);复制代码

Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。 

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
}); 复制代码

6. store.subscribe():Store 容许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。 


redux流程机制: 



中间件使用介绍: 

1.redux-logger为例:将它放在applyMiddleware方法之中,传入createStore方法,就完成了store.dispatch()的功能加强,注意applyMiddleware(thunk, promise, logger)的参数顺序是固定的。 

2.redux-thunk:使用redux-thunk中间件,改造store.dispatch,使得后者能够接受函数做为参数(如图异步action)。

 

3.redux-promise:就是让 Action Creator 返回一个 Promise 对象。 

const fetchPosts = 
  (dispatch, postTitle) => new Promise(function (resolve, reject) {
     dispatch(requestPosts(postTitle));
     return fetch(`/some/API/${postTitle}.json`)
       .then(response => {
         type: 'FETCH_POSTS',
         payload: response.json()
       });
});复制代码


附:中间件applyMiddleware源码

相关文章
相关标签/搜索