本文へスキップ

applyMiddleware(...middleware)

概要

ミドルウェアは、カスタム機能でReduxを拡張するための推奨方法です。ミドルウェアを使用すると、ストアのdispatchメソッドをラップして、様々な機能を追加できます。ミドルウェアの重要な機能は、コンポーザブルであることです。複数のミドルウェアを組み合わせることができ、各ミドルウェアは、チェーンの前後にあるミドルウェアについて何も知る必要がありません。

警告

applyMiddlewareを直接呼び出す必要はありません。Redux ToolkitのconfigureStoreメソッドは、デフォルトのミドルウェアセットをストアに自動的に追加するか、追加するミドルウェアのリストを受け入れることができます。

ミドルウェアの最も一般的なユースケースは、多くのボイラープレートコードやRxのようなライブラリへの依存なしで非同期アクションをサポートすることです。これは、通常のアクションに加えて非同期アクションをディスパッチできるようにすることで実現されます。

例えば、redux-thunkを使用すると、アクションクリエイターは関数をディスパッチすることで制御を反転できます。それらはdispatchを引数として受け取り、非同期的に呼び出すことができます。このような関数はthunkと呼ばれます。ミドルウェアのもう1つの例としてredux-promiseがあります。これにより、Promise非同期アクションをディスパッチし、Promiseが解決されたときに通常のアクションをディスパッチできます。

元のRedux createStoreメソッドは、ミドルウェアをすぐに認識しません。その動作を追加するには、applyMiddlewareで構成する必要があります。ただし、Redux ToolkitのconfigureStoreメソッドは、デフォルトでミドルウェアサポートを自動的に追加します。

引数

  • ...middleware (引数): Redux ミドルウェアAPIに準拠した関数。各ミドルウェアは、Storedispatch関数とgetState関数を名前付き引数として受け取り、関数を返します。その関数は、次のミドルウェアのdispatchメソッドを与えられ、引数を変更したり、異なる時間に呼び出したり、まったく呼び出さない可能性のあるnext(action)を呼び出すactionの関数を返すことが期待されます。チェーンの最後のミドルウェアは、実際のストアのdispatchメソッドをnextパラメーターとして受け取り、チェーンを終了します。したがって、ミドルウェアのシグネチャは({ getState, dispatch }) => next => actionです。

戻り値

(関数) 指定されたミドルウェアを適用するストアエンハンサー。ストアエンハンサーのシグネチャはcreateStore => createStoreですが、それを適用する最も簡単な方法は、最後のenhancer引数としてcreateStore()に渡すことです。

例:カスタムロガーミドルウェア

import { createStore, applyMiddleware } from 'redux'
import todos from './reducers'

function logger({ getState }) {
return next => action => {
console.log('will dispatch', action)

// Call the next dispatch method in the middleware chain.
const returnValue = next(action)

console.log('state after dispatch', getState())

// This will likely be the action itself, unless
// a middleware further in chain changed it.
return returnValue
}
}

const store = createStore(todos, ['Use Redux'], applyMiddleware(logger))

store.dispatch({
type: 'ADD_TODO',
text: 'Understand the middleware'
})
// (These lines will be logged by the middleware:)
// will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }
// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]

例:非同期アクションのためのThunkミドルウェアの使用

import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import * as reducers from './reducers'

const reducer = combineReducers(reducers)
// applyMiddleware supercharges createStore with middleware:
const store = createStore(reducer, applyMiddleware(thunk))

function fetchSecretSauce() {
return fetch('https://www.google.com/search?q=secret+sauce')
}

// These are the normal action creators you have seen so far.
// The actions they return can be dispatched without any middleware.
// However, they only express “facts” and not the “async flow”.
function makeASandwich(forPerson, secretSauce) {
return {
type: 'MAKE_SANDWICH',
forPerson,
secretSauce
}
}

function apologize(fromPerson, toPerson, error) {
return {
type: 'APOLOGIZE',
fromPerson,
toPerson,
error
}
}

function withdrawMoney(amount) {
return {
type: 'WITHDRAW',
amount
}
}

// Even without middleware, you can dispatch an action:
store.dispatch(withdrawMoney(100))

// But what do you do when you need to start an asynchronous action,
// such as an API call, or a router transition?

// Meet thunks.
// A thunk is a function that returns a function.
// This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
)
}
}

// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!
store.dispatch(makeASandwichWithSecretSauce('Me'))

// It even takes care to return the thunk's return value
// from the dispatch, so I can chain Promises as long as I return them.
store.dispatch(makeASandwichWithSecretSauce('My wife')).then(() => {
console.log('Done!')
})

// In fact I can write action creators that dispatch
// actions and async actions from other action creators,
// and I can build my control flow with Promises.
function makeSandwichesForEverybody() {
return function (dispatch, getState) {
if (!getState().sandwiches.isShopOpen) {
// You don't have to return Promises, but it's a handy convention
// so the caller can always call .then() on async dispatch result.
return Promise.resolve()
}

// We can dispatch both plain object actions and other thunks,
// which lets us compose the asynchronous actions in a single flow.
return dispatch(makeASandwichWithSecretSauce('My Grandma'))
.then(() =>
Promise.all([
dispatch(makeASandwichWithSecretSauce('Me')),
dispatch(makeASandwichWithSecretSauce('My wife'))
])
)
.then(() => dispatch(makeASandwichWithSecretSauce('Our kids')))
.then(() =>
dispatch(
getState().myMoney > 42
? withdrawMoney(42)
: apologize('Me', 'The Sandwich Shop')
)
)
}
}

// This is very useful for server side rendering, because I can wait
// until data is available, then synchronously render the app.

import { renderToString } from 'react-dom/server'

store
.dispatch(makeSandwichesForEverybody())
.then(() => response.send(renderToString(<MyApp store={store} />)))

// I can also dispatch a thunk async action from a component
// any time its props change to load the missing data.

import React from 'react'
import { connect } from 'react-redux'

function SandwichShop(props) {
const { dispatch, forPerson } = props

useEffect(() => {
dispatch(makeASandwichWithSecretSauce(forPerson))
}, [forPerson])

return <p>{this.props.sandwiches.join('mustard')}</p>
}

export default connect(state => ({
sandwiches: state.sandwiches
}))(SandwichShop)

ヒント

  • ミドルウェアは、ストアのdispatch関数をラップするだけです。技術的には、ミドルウェアができることは何でも、すべてのdispatch呼び出しをラップすることで手動で行うことができますが、これを1か所で管理し、プロジェクト全体の規模でアクション変換を定義する方が簡単です。

  • applyMiddlewareに加えて他のストアエンハンサーを使用する場合は、ミドルウェアは非同期である可能性があるため、合成チェーンでapplyMiddlewareの前に配置してください。たとえば、redux-devtoolsの前に配置する必要があります。そうしないと、DevToolsはPromiseミドルウェアなどが発行する生のアクションを見ることができません。

  • ミドルウェアを条件付きで適用する場合は、必要になったときにのみインポートしてください。

    let middleware = [a, b]
    if (process.env.NODE_ENV !== 'production') {
    const c = require('some-debug-middleware')
    const d = require('another-debug-middleware')
    middleware = [...middleware, c, d]
    }

    const store = createStore(
    reducer,
    preloadedState,
    applyMiddleware(...middleware)
    )

    これにより、バンドリングツールは不要なモジュールを簡単に切り捨てることができ、ビルドのサイズを削減できます。

  • applyMiddleware自体は何だろうかと疑問に思ったことはありませんか?それは、ミドルウェア自体よりも強力な拡張メカニズムであるはずです。実際、applyMiddlewareは、ストアエンハンサーと呼ばれる最も強力なRedux拡張メカニズムの例です。自分でストアエンハンサーを作成したいと思うことはほとんどないでしょう。redux-devtoolsもストアエンハンサーの例です。ミドルウェアはストアエンハンサーほど強力ではありませんが、記述は容易です。

  • ミドルウェアは実際よりもはるかに複雑に聞こえます。ミドルウェアを本当に理解するには、既存のミドルウェアがどのように機能するかを見て、自分で作成してみるのが一番です。関数のネストは恐ろしいように見えるかもしれませんが、ほとんどのミドルウェアは実際には10行程度で、ネストとコンポーザビリティがミドルウェアシステムを強力にしています。

  • 複数のストアエンハンサーを適用するには、compose()を使用できます。