Reselect是一个Redux的选择器库,灵感来源于NuclearJS。
Selector可以计算衍生的数据,可以让Redux存储尽可能少的state。
Selector非常高效,除非某个参数发生变化,否则不会发生计算过程。
Selector是可组合的,它们可以输入、传递到其他的选择器。
示例:
import { createSelector } from 'reselect'const shopItemsSelector = state => state.shop.itemsconst taxPercentSelector = state => state.shop.taxPercentconst 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.15console.log(taxSelector(exampleState)) // 0.172console.log(totalSelector(exampleState)) // { total: 2.322 }
评论