redux的一些外掛總結(redux-actions,reselect)

看風景就發表於2018-08-24

redux本身還是過於簡單,實際使用的時候需要配合許多外掛。

下面是一些外掛與vuex的功能對比

redux-actions <=> vuex的mutation的寫法

reselect <=> vuex的getters

redux-react <=> vuex的mapState,mapActions,mapMutations

1.redux-actions

redux-actions是用來簡化action和reducer的寫法。
redux-actions的常用的API分別是createAction、createActions、handleAction、handleActions、combineActions

簡化前後的對比如下:

1.建立Action

//簡化前寫法
const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
const COUNTER_DECREMENT = 'COUNTER_DECREMENT';

export const incrementCounter = () => ({
  type: COUNTER_INCREMENT,
});
export const decrementCounter = () => ({
  type: COUNTER_DECREMENT,
});

//簡化後寫法
const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
const COUNTER_DECREMENT = 'COUNTER_DECREMENT';
export const incrementCounter = createAction('COUNTER_INCREMENT');
export const decrementCounter = createAction('COUNTER_DECREMENT');

2.建立Reducer

//簡化前寫法
export default (state = 0, action) => {
  switch (action.type) {
    case COUNTER_INCREMENT:
      return state + 1;
    case COUNTER_DECREMENT:
      return state - 1;
    default:
      return state;
  }
}

//簡化後寫法
export default handleActions({
  [incrementCounter](state) {
    return state + 1;
  },
  [decrementCounter](state) {
    return state - 1;
  },
}, 0)

2.reselect

reselect可以用來產生一些依賴變數,產生依賴變數的函式稱為selector。
reselect不僅可以用於redux,其他有依賴屬性的地方也可以使用。

Selector可以計算衍生的資料,可以讓Redux做到儲存儘可能少的state
Selector會快取結果,只有在某個引數發生變化的時候才發生計算過程
Selector是可以組合的,他們可以作為輸入,傳遞到其他的selector

例如:

import { createSelector } from 'reselect'

const shopItemsSelector = state => state.shop.items
const taxPercentSelector = state => state.shop.taxPercent

const subtotalSelector = createSelector(
  shopItemsSelector,
  items => items.reduce((acc, item) => acc + item.value, 0)
)

const taxSelector = createSelector(
  subtotalSelector,
  taxPercentSelector,
  (subtotal, taxPercent) => subtotal * (taxPercent / 100)
)

export const totalSelector = createSelector(
  subtotalSelector,
  taxSelector,
  (subtotal, tax) => ({ total: subtotal + tax })
)

let exampleState = {
  shop: {
    taxPercent: 8,
    items: [
      { name: 'apple', value: 1.20 },
      { name: 'orange', value: 0.95 },
    ]
  }
}

console.log(subtotalSelector(exampleState)) // 2.15
console.log(taxSelector(exampleState))      // 0.172
console.log(totalSelector(exampleState))    // { total: 2.322 }

reselect的詳細用法,可以參考https://www.jianshu.com/p/6e38c66366cd

 

 

參考:https://majing.io/posts/10000006441202

相關文章