redux学习笔记归纳

229 阅读2分钟
设计思想:

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

(2)所有的状态,保存在一个对象里面。


核心源码:



基本概念: 

1.Store:就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。 

const store = createStore(fn); 

2.State:Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。 

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。 

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

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

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源码