ソース概要はReduxのを読みます

はじめにReduxの

Reduxのこれらのメソッドを公開する私たちを与えます

{
  createStore,
  combineReducers,
  bindActionCreators,
  applyMiddleware,
  compose
}

私たちは紹介して回します

CREATESTORE

文言の店舗を作成します:

let store = createStore(reducer, preloadedState, enhancer);

3つのCREATESTORE、preloadedState減速パラメータ、エンハンサー、後者の2つのパラメータは、オプションで
、我々は2つのパラメータのみを通過する際、第二の引数は、例えば、関数です。

let store = createStore(reducer, enhancer);

このソースを読むことによって、

if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState
    preloadedState = undefined
  }

私たちは、CREATESTORE上記のように書き換えることがあることを知っています:

createStore(educer, undefined, enhancer)

そして、ソースコードを読み取ることで、この:

if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }

    return enhancer(createStore)(reducer, preloadedState)
  }

コールは再び道を変えたことがわかります、それは少なく、このようになり

enhancer(createStore)(reducer, undefined)

この方法の例は、したがってCREATESTORE、以下の二つは等価です。

第一种
const store = createStore(reducers, applyMiddleware(routeMiddleware, sagaMiddleware, postRedirectMiddleware, pageSizeMiddleware));


第二种
const store = applyMiddleware(routeMiddleware, sagaMiddleware, postRedirectMiddleware, pageSizeMiddleware)(createStore)(reducers);

最後に、ストアは、返されるオブジェクトは、当社の使用のためにいくつかのメソッドを提供します

dispatch,
subscribe,
getState,
replaceReducer,

getStateをであるcurrentStateの、状態の合計値を得るために使用しました

購読開発者が派遣を呼び出すために電源を入れたときに実行される複数のリスナー関数を登録します

ディスパッチ引数のは、オブジェクトアクション、直接実行される減速(アクション)方法であり、ディスパッチがアクションを実行するために返された後にバッチ実行内容は、リスニングサブスクライブ

replaceReducerこのメソッドは非同期を使用して1つのアプリケーションで利用することができ、現在の減速を交換、例えば、このページの後、減速、我々はCREATESTOREへのすべてのワンタイム初期化減速を望んでいないが、非同期ページの取得時にプラス古い減速する前に、replaceReducer法による最新に戻します。この方法の利点は、当然のことながら、Reduxのツールのこと、デベロッパーツールは非常に多くの情報を表示しない、それだけで私たちの発展により助長、訪問した情報ページが表示されます減少した減速に起因して、店舗の量も少なくなります、ページがより速く実行されます。

combineReducers

ソース

export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        warning(`No reducer provided for key "${key}"`)
      }
    }

    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key]
    }
  }
  const finalReducerKeys = Object.keys(finalReducers)

  let unexpectedKeyCache
  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {}
  }

  let shapeAssertionError
  try {
    assertReducerShape(finalReducers)
  } catch (e) {
    shapeAssertionError = e
  }

  return function combination(state = {}, action) {
    if (shapeAssertionError) {
      throw shapeAssertionError
    }

    if (process.env.NODE_ENV !== 'production') {
      const warningMessage = getUnexpectedStateShapeWarningMessage(
        state,
        finalReducers,
        action,
        unexpectedKeyCache
      )
      if (warningMessage) {
        warning(warningMessage)
      }
    }

    let hasChanged = false
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      const previousStateForKey = state[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        const errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      nextState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}

通常、我々はこれを使用します

combineReducers({
    a:reducer1,
    b:reducer2
})

reducer1は関数であり、任意の自然combineReducersリターンが関数であるが、減速がそれぞれ再びトラバースされ、最後に返されたデータ構造

{
    a:state1,
    b:state2
}

そして、私たちはユニークなパスパスに置き換えBに入れた場合、例えば対応するフォルダの各ページのためのプロジェクトファイルのパス:

combineReducers({
    'component/page1/info/':reducer1,
    'component/page2/user/':reducer2
})

このデータの時に取るように状態を取得
[「コンポーネント/ページ1 /インフォ状態が /」] ファイルではありませんモジュラーフォルダのパスを介して達成することができる、もちろん我々はまだ離れモジュラーから小さな一歩です、何のマニュアルがないこと完成を通過するが、ビルドツールへの書き込みパスパス(ローダーをWebPACKの)。

コン

ソース

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

コードの後パーソナル感触COMPOSE(A、B、C)(D)は(B(C(D)))であり、任意のその後コンポーズ後に返されるパラメータを受け入れることができる機能である、コード内のCOMPOSEは後述それは関与しました。

applyMiddleware

ソース

export default function applyMiddleware(...middlewares) {
  return createStore => (...args) => {
    const store = createStore(...args)
    let dispatch = () => {
      throw new Error(
        `Dispatching while constructing your middleware is not allowed. ` +
          `Other middleware would not be applied to this dispatch.`
      )
    }
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

のストアを作成する方法:


let store = applyMiddleware(middleware1,middleware2,middleware3)(createStore)(reducers)

ミドルウェアmiddleware1コード

function middleware1({ getState }) {
  return (next) => (action) => {
    console.log('will dispatch', action)
    let returnValue = next(action)
    console.log('state after dispatch', getState())
    return returnValue
  }
}

applyMiddleware中間体、中間作用減速複数のスイッチ、最初の実行コードミドルウェアの前に実行されるパラメータに渡さ。

ソースコードに対応するパラメータに関して、その後
の例のパラメータは、middleware2等価middleware1 ソースを基準に...ミドルウェア、
の例 CREATESTOREのに対応するパラメータソース参照CREATESTOREへ
の例対応するパラメータ減速ソースを基準に...引数。

のソース

const store = createStore(...args)

後で使用するためにオブジェクトストアを取得し、対応getStateを、getStateを()メソッドでmiddlewareAPIレーンgetStateをストアオブジェクトはcurrentStateの、すなわち、総データReduxのオブジェクトツリーを取得します。

chain = middlewares.map(middleware => middleware(middlewareAPI))

middlewareAPI getStateをこの方法では、中間currenStateを得るために提供する、アレイチェーンは、この時間は、関数の戻り値の関数で取得しました。

このコード行は、よりエキサイティング

dispatch = compose(...chain)(store.dispatch)

参照として、まずstore.dispatch最も原始的な方法で、

dispatch(action)

就相当于
compose(...chain)(store.dispatch)(action),

同时也相当于
middleware1(middleware2(middleware3((store.dispatch))))(action),

もちろん、ここではmiddleware1は3層のみの代わりに、閉じた機能パッケージの体内で本来の機能を有しています。

最先执行的是middleware1,
返回了next(action),

也就相当于
middleware2(middleware3((store.dispatch)))(action),

执行完后返回next(action)
就相当于middleware3((store.dispatch))(action),

执行完后返回next(action)
就相当于store.dispatch(action)

私たちは、全体のプロセスを考え出した、実装プロセスのapplyMiddlewareミドルウェアは、次の(アクション)を維持することです、
しかし、次の転送の前に、次のディスパッチを実行するだけで、最後は最後の中間に他のミドルウェア、発送方法を表します作品の実装インチ

個人的に私はこの場所コンの後に書かれたコンバインがよりエキサイティングなと思うし、デザインは非常に賢いです。

おすすめ

転載: www.cnblogs.com/homehtml/p/12055391.html