Redux解讀

小編發表於2018-05-28

Redux核心運作流程

這裡寫圖片描述

Redux的基本原則

Redux的基本原則 1.唯一資料來源 應用的狀態資料應該只儲存在唯一的一個Store上,即 State 樹。 2.儲存狀態只讀 不能直接修改state的值,必須通過派發action物件完成。通過getState()獲取值 3.資料改變只能通過純函式 這裡的純函式就是reducer,函式的返回結果必須有兩個引數stateaction決定

createStore原始碼

export default function createStore(reducer, initialState) {
  
  var currentReducer = reducer;
  var currentState = initialState;
  var listeners = [];
  var isDispatching = false;
  
  /**
   * Reads the state tree managed by the store.
   *
   * @returns {any} The current state tree of your application.
   */
  function getState() {
    return currentState;
  }

    /**
   * Adds a change listener. It will be called any time an action is dispatched,
   * and some part of the state tree may potentially have changed. You may then
   * call `getState()` to read the current state tree inside the callback.
   *
   * @param {Function} listener A callback to be invoked on every dispatch.
   * @returns {Function} A function to remove this change listener.
   */
  function subscribe(listener) {
    listeners.push(listener);

    return function unsubscribe() {
      var index = listeners.indexOf(listener);
      listeners.splice(index, 1);
    };
  }
  
  //根據自定義的reducer處理state和action,並返回新的state。同時觸發listener的呼叫
  function dispatch(action) {
    try {
      isDispatching = true;
      //返回新的state
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }
	//觸發listener呼叫
    listeners.slice().forEach(listener => listener());
    return action;
  }

  // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.
  // Store初始化,會執行一次dispatch
  dispatch({ type: ActionTypes.INIT });

  return {
    dispatch,
    subscribe,
    getState,
    replaceReducer
  };
}
複製程式碼

描述

1.建立Store,持有一個State樹(State Tree) 2.改變Store中的資料,唯一的方式就是呼叫dispatch()方法 3.應用中僅僅存在一個Store 4.指定狀態樹的不同部分應該如何響應動作(action) 5.通過使用combineReducers,將幾個reducer合併成一個reducer函式

Redux的核心是一個store,這個storeRedux提供的createStore(reducers[,initialState])方法生成。要想生成store,必須傳入reducers,第二個引數則可選

引數

  • reducer reducer是一個純函式。給定當前state樹和要處理的action的函式,返回新的state樹。
reducer(previousState, action) => newState
複製程式碼
  • initialState 初始化狀態。

關鍵方法

  • getState() 獲取store中當前的狀態。
  • dispatch(action) 分發一個action,並返回這個action。這是唯一能改變store中資料的方式,且觸發listener的呼叫
  • subscribe(listener) 註冊一個監聽者,它在store發生變化的時候被呼叫
  • replaceReducer(nextReducer) 更新當前store裡的reducer,一般只會在開發模式中呼叫該方法。

應用

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'

const store = createStore(counter)
const rootEl = document.getElementById('root')

const render = () => ReactDOM.render(
  <Counter
    value={store.getState()}
    onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
    onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
  />,
  rootEl
)

render()
store.subscribe(render)

複製程式碼

作用域鏈角度看

createStore
    |--currentState
    |
    |--reducer()
    |   |--currentState, action
    |
    |--getState()
    |
    |--dispatch()
    |	|--action
複製程式碼

相關文章