Action 創(chuàng)建函數(shù) 和 中間件

Action 創(chuàng)建函數(shù)

編寫

function increment(){
    return { type: 'INCREMENT' }
}

發(fā)起

store.dispatch( increment() )

如果不想每次都 store.dispatch 發(fā)起 action.

const increment = () => dispatch( increment() )

_使用 react-redux 將 action 創(chuàng)建函數(shù)綁定到 React 組件上時, bindActionCreators() 方法自動將多個 action 創(chuàng)建函數(shù)封裝成可以直接調(diào)用的普通函數(shù) _

意義

Action 創(chuàng)建函數(shù)更大的意義在于封裝邏輯, 而不是創(chuàng)建 action 對象, 比如說可以在里面添加一些判斷邏輯(只允許奇數(shù)相加等). 使用 action 創(chuàng)建函數(shù)封裝邏輯是 react 與 redux 配合的最佳實踐. 當(dāng)所有邏輯被轉(zhuǎn)移到 redux后, react 就只負(fù)責(zé)渲染界面, 并發(fā)起 action.

中間件會讓 action 創(chuàng)建函數(shù)返回更多的格式( 函數(shù) ), 增強(qiáng) action 創(chuàng)建函數(shù)的功能, 并讓它處理負(fù)責(zé)邏輯.

Redux Thunk 中間件

redux thunk 中間件可以讓 action 創(chuàng)建函數(shù)先不返回 action 對象, 而是返回一個函數(shù).

通過這個函數(shù)延遲 dispatch 或 某些情況下才 dispatch. 這個內(nèi)部函數(shù)接受 store 的兩個方法 dispatch 和 getState 作為參數(shù).

function incrementIfOdd(){
  return ( dispatch, getState() ) => {
      const value = getState();
      if (value % 2 === 0){
          return;
      }
      dispatch( increment() );
  }
}

要使用, 先激活

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const store = createStore( counter, applyMiddleware( thunk ) );

function increment(){
    return { type: 'INCREMENT' }
}

function incrementIfOdd(){
  return ( dispatch, getState() ) => {
      const value = getState();
      if (value % 2 === 0){
          return;
      }
      dispatch( increment() );
  }
}

function incrementAsync(){
  return ( dispatch ) => {
     setTimeout( ()=>{
        dispatch( increment() ) ;
     } )
  }
}

// 發(fā)起action, 上面三個都是 action 創(chuàng)建函數(shù)

store.dispatch( increment() )
store.dispatch( incrementIfOdd() )
store.dispatch( incrementAsync() )
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容