针对输入的参数做计算,只要所有相关的参数值没变,不再重新计算而是直接使用之前缓存的结果。

    1. import { createSelector } from 'reselect'
    2. const selectShopItems = state => state.shop.items
    3. const selectTaxPercent = state => state.shop.taxPercent
    4. const selectSubtotal = createSelector(selectShopItems, items =>
    5. items.reduce((subtotal, item) => subtotal + item.value, 0)
    6. )
    7. const selectTax = createSelector(
    8. selectSubtotal,
    9. selectTaxPercent,
    10. (subtotal, taxPercent) => subtotal * (taxPercent / 100)
    11. )
    12. const selectTotal = createSelector(
    13. selectSubtotal,
    14. selectTax,
    15. (subtotal, tax) => ({ total: subtotal + tax })
    16. )
    17. const exampleState = {
    18. shop: {
    19. taxPercent: 8,
    20. items: [
    21. { name: 'apple', value: 1.2 },
    22. { name: 'orange', value: 0.95 }
    23. ]
    24. }
    25. }
    26. console.log(selectSubtotal(exampleState)) // 2.15
    27. console.log(selectTax(exampleState)) // 0.172
    28. console.log(selectTotal(exampleState)) // { total: 2.322 }