开发者社区> 问答> 正文

#React 举一个重新选择用法的例子吗?

#React 举一个重新选择用法的例子吗?

展开
收起
因为相信,所以看见。 2020-05-08 10:14:07 285 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    让我们通过简化的Reselect进行计算和不同数量的装运订单:

    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 }
    
    2020-05-08 10:15:36
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载