redux作業でよく使われるミドルウェア

7187 ワード

仕事でよく使うミドルウェア
redux-thunk
これが私たちが実現したthunkミドルウェアで、使い方は同じです.
  • ダウンロードミドルウェア
  • npm install redux-thunk
  • は、ミドルウェアを導入する、ミドルウェア
  • を登録する.
    import thunk from 'redux-thunk'
    
    import { applyMiddleware } from 'redux'
    export const store = createStore(RootReducer, applyMiddleware(thunk))

    今から楽しく使えます
    redux-saga
    redux-sagaでカウンタ延期機能を実現
    Redux-thunk機能と一致するが、redux-thunkよりも強力であり、redux-sagaは非同期操作をActionCreatorファイルから抽出し、個別のファイルに置くことができ、プロジェクトコードをより維持することができる.
    takeEvery:actionを受信するために使用され、最初のパラメータの場合に受信するactionタイプ文字列、2番目のパラメータは実行する非同期メソッドです.
    put:actionがdispatchメソッドと一致することをトリガーするために使用されます
    generator関数をデフォルトでエクスポートする必要があります
  • redux-saga
  • をダウンロード
    npm install redux-saga
  • redux-sagaミドルウェア
  • を作成する
    import createSagaMiddleware form 'redux-saga'
    
    const sagaMiddleware = createSagaMiddleware()
    
    createStore(RootReducer, applyMiddleware(sagaMiddleware))
  • 非同期アクションaction
  • を作成
    export const increment_async = () => ({type: INCREMENT_ASYNC})
  • sagaを使用して非同期操作のactionをブロックし、非同期操作が完了するのを待って同期変更を実行するaction
  • .
    import  { takeEvery, put, delay } from 'redux-saga/effects'
    import { increment } from '../actions/counter.actions'
    import { INCREMENT_ASYNC } from '../const/counter.const'
    
    function* increment_async_fn () {
        yield delay(2000)
        yield put(increment(10))
    }
    
    export default function* counterSage () {
        yield takeEvery(INCREMENT_ASYNC, increment_async_fn)
    }
  • saga
  • を起動
    import createSagaMiddleware from 'redux-saga'
    import counterSage from './sagas/counter.sagas'
    
    const sagaMiddleware = createSagaMiddleware()
    
    export const store = createStore(RootReducer, applyMiddleware(sagaMiddleware))
    
    //           createStore  
    sagaMiddleware.run(counterSage)

    redux-sagaにおけるactionパラメータ
  • ビューにおける入力パラメータ
  • actionでパラメータを受け入れactionに追加する
  • export const increment_async = payload => ({type: INCREMENT_ASYNC, payload})
  • sagaミドルウェアでパラメータを受信し、変更操作を実行するaction
  • に渡す.
    function* increment_async_fn (action) {
        console.log(action)
        yield delay(2000)
        yield put(increment(action.payload))
    }

    sagaファイルの分割とマージ
    sagaを使用してポップアップ・ボックスの表示と非表示を遅延
  • 非同期actionを作成し、action.typeは定数
  • として定義される
    export const show_async = () => ({type: SHOWMODAL_ASYNC})
    
    //     
    export const SHOWMODAL_ASYNC = 'showModal_async'
  • sagaで非同期acitonをブロックし、非同期操作を実行すると同期変更action
  • をトリガする.
    import  { takeEvery, put, delay } from 'redux-saga/effects'
    import { show } from '../actions/modal.actions'
    import { SHOWMODAL_ASYNC } from '../const/modal.const'
    function* showModal_async_fn (){
        yield delay(2000)
        yield put(show())
    }
    export default function* counterSage () {
        yield takeEvery(SHOWMODAL_ASYNC, showModal_async_fn)
    }
  • ビューで非同期action
  • をトリガー
    // function Modal ({ show_async }) {} 
    

    このsagaファイルでは、ポップアップボックスを受信した非同期actionとカウンタ非同期actionが受信されていることがわかりました.このような非同期操作が多すぎると、コードが肥大化してメンテナンスできないので、sagaを分割して統合する必要があります.
    合併saga
    sagaをマージするにはallメソッドが必要です.allメソッドは配列パラメータを受信します.この配列のメンバーは私たちが分離したsagaの呼び出しです.
  • src/store/sagas/modalを作成します.sagas.jsファイル、ポップアップボックスのコードを現在のファイル
  • に抽出する
    import  { takeEvery, put, delay } from 'redux-saga/effects'
    import { show } from '../actions/modal.actions'
    import { SHOWMODAL_ASYNC } from '../const/modal.const'
    
    function* showModal_async_fn (){
        yield delay(2000)
        yield put(show())
    }
    
    export default function* modalSaga (){
        yield takeEvery(SHOWMODAL_ASYNC, showModal_async_fn)
    }
  • src/store/sagas/rootを作成します.saga.jsファイル、インポート作成sagaファイルを統合
  • import { all } from 'redux-saga/effects'
    import counterSaga from './counter.sagas'
    import modalSaga from './modal.sagas'
    
    
    export default function* rootSaga() {
        yield all([
            counterSaga(),
            modalSaga()
        ])
    }
  • 実行saga転送をrootsaga
  • に変更
    import rootSaga from './sagas/root.saga'
    
    const sagaMiddleware = createSagaMiddleware()
    
    
    
    export const store = createStore(RootReducer, applyMiddleware(sagaMiddleware))
    
    //           createStore  
    sagaMiddleware.run(rootSaga)

    ###redux-actionsミドルウェア
    Redux-actionsは、actionコードとreducerコードを簡略化するのに役立ちます.
    reduxプロセスにおける大量のテンプレートコードの読み書きは苦痛であり,redux-actionsを用いることでacitonとreducerの処理を簡略化できる.
    redux-actionsのダウンロード
    npm install redux-actions

    アクションの作成
    createActionはパラメータとして文字列を受信します.この文字列はactionオブジェクトのtype値で、戻り値は自分で定義されます.
    ActionCreate関数は、actionをトリガして受信するときにcreateActionの戻り値を使用するだけでいいので、type値を定数に設定する必要はありません.
    import { createAction } from 'redux-actions'
    
    const increment_action = createAction('increment')
    const decrement_action = createAction('decrement')

    reducerの作成
    createReducerは2つのパラメータを受信し、最初のパラメータはオブジェクトであり、オブジェクトのkeyはcreateActionで作成されたactionであり、オブジェクトのvalueはactionの操作を実行する
    2番目のパラメータは初期値です
    import { handleActions as createReducer } from 'redux-actions'
    import { increment_action, decrement_action} from '../actions/counter.action'
    
    const initialState = {count: 0}
    const counterReducer = createReducer({
      [increment_action]: (state, action) => ({count: state.count + 1}),           
      [decrement_action]: (state, action) => ({count: state.count + 1})
    }, initialState)
    export default counterReducer

    redux-actionsでカウンタケースを実現
  • redux-actionsでaction
  • を作成する
    import { createAction } from 'redux-actions'
    
    export const increment = createAction('increment')
    export const decrement = createAction('decrement')
  • redux-actionsでreducer
  • を作成する
    import { increment, decrement } from './../actions/counter.actions'
    import { handleActions as createReducer } from 'redux-actions'
    
    const initialState = {
        count: 0
    }
    
    const handIncrement = (state, action) =>({count: state.count + 1})
    const handDecrement = (state, action) =>({count: state.count - 1})
    
    export default createReducer({
        [increment]: handIncrement,
        [decrement]: handDecrement
    }, initialState)
  • 伝達パラメータはビューで伝達する、直接reducerで
  • を受信する.
    //   
    function Count({count,increment,decrement}) {
        return 
    {count}
    } // reducer const handIncrement = (state, action) =>({count: state.count + action.payload}) const handDecrement = (state, action) =>({count: state.count - action.payload})

    原文住所:https://kspf.xyz/archives/22/