2017-04-14 69 views
1

我是新選擇器。我創建了以下的: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

你可以只提取部分減少到它自己的功能是這樣的:

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) 

我希望這是有幫助的。