2重新选择输入选择器共享太多代码。如何重构?

时间:2016-03-05 13:40:52

标签: javascript reactjs redux

我想根据选定的城市选择车库和零售商。

这就是我现在所拥有的:

const garagesSelector = state => state.garages
const retailersSelector = state => state.retailers
const selectedCitySelector = state => state.cities.selected

const garagesInCitySelector = createSelector(
  garagesSelector,
  selectedCity,
  (garages, city_id) => garages.filter(garage => garage.city_id === city_id)
)

const retailersInCitySelector = createSelector(
  retailersSelector,
  selectedCity,
  (retailers, city_id) => retailers.filter(retailer => retailer.city_id === city_id)
)

他们基本上做同样的事情只是他们操作的项目选择器不同。 我想象一个构造,items可以是任何返回数组的选择器。

类似的东西:

const inCitySelector = createSelector(
  items,
  selectedCity,
  (items, city_id) => items.filter(garage => item.city_id === city_id)
)
const garagesInCitySelector = inCitySelector(garagesSelector)
const retailersInCitySelector = inCitySelector(retailersSelector)

更新

const filterByCity = (items, city_id) => item => item.city_id === city_id

const garagesInCitySelector = createSelector(garagesSelector, selectedCity, filterByCity)
const retailersInCitySelector = createSelector(retailersSelector, selectedCity, filterByCity)

但似乎对我来说代码太多了。

0 个答案:

没有答案