Redux / Reselect - 选择器重用
Redux / Reselect - selector reusing
我是选择器的新手。我创建了以下:
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' 行?
您可以像这样将 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)
希望对您有所帮助。
我是选择器的新手。我创建了以下:
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' 行?
您可以像这样将 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)
希望对您有所帮助。