Redux / Reselect - 选择器重用

时间:2017-04-14 11:57:54

标签: redux reselect

我是选择者的新手。我创建了以下内容:

import { createSelector } from 'reselect';

const getValues = (state) => state.grid; // [3, 4, 7, 3, 2, 7, 3,...]
const getTiles = (state) => state.tiles; // [0, 1, 0, 1, 0, 0, 1,...]

// counts selected tiles (ie. adds up all the 1s)
export const getSelected = createSelector(
  [getTiles],
  tiles => tiles.reduce((acc, elem) => acc + elem, 0)
);

// displays only values of selected tiles, for the rest it shows 0
export const showSelected = createSelector(
  [getTiles, getValues],
  (tiles, grid) => tiles.map((idx, i) => (idx === 1 ? grid[i] : 0))
);



  export const addSelected = createSelector(
  [showSelected]
  .....
);

/*
export const addSelected = createSelector(
  [showSelected],
  coun => coun.reduce((acc, elem) => acc + elem, 0)
);

*/

第三个选择器(addSelected - 最后一个底部,注释掉的版本)基本上与第一个选择器(使用不同的输入)做同样的事情。如何使它更通用,以便我可以重复使用它而不是写整个' reduce'又一次?

1 个答案:

答案 0 :(得分:2)

你可以将reduce部分提取到它自己的函数中:

import { createSelector } from 'reselect'

...

// addElements adds all elements from given array
const addElements = elements =>
  elements.reduce((acc, elem) => acc + elem, 0)

export const getSelected = createSelector([getTiles], addElements)

export const addSelected = createSelector([showSelected], addElements)

我希望这很有帮助。