2016-11-13 86 views
1

比方說,我有以下狀態:看起坐在終極版減速器

state = { 
    products: { 
    50: { 
     sku: "000", 
     name: "A Product", 
     category: 123, 
     ... 
    } 
    }, 
    categories: { 
    123: { 
     name: "Some Category", 
     parentCategory: 100, 
     department: "Electronics" 
    } 
    }, 
    filteredProducts: [50] 
} 

我希望能夠過濾基於類別的產品。不過,我需要根據類別的多個屬性進行過濾。即我可能想要獲得電子部門中的所有類別,或者我可能想要獲得ID爲123的類別及其所有子類別。

這是一個人爲設計的例子,它與我想要達到的要求非常接近,但它更容易理解,所以請耐心等待。我知道在這個特定的例子中,我可以使用類似重新選擇的東西,但假設我需要爲產品縮減器進行類別查找,我的選擇是什麼?

回答

1

您可以使用reselect如你所說,並提出一些選擇與參數重新使用這些選擇從產品類別是如下:

讓你category/selectors文件如下:

import { createSelector } from 'reselect'; 

const categoriesSelector = state => state.categories; 

const selectCategoryById = id => { 
    return createSelector(
    categoriesSelector, 
    categories => categories[id] 
); 
} 

const selectCategoryByName = name => { 
    return createSelector(
    categoriesSelector, 
    categories => categories.filter(c => c.name === name) 
); 
} 

export default { 
    categoriesSelector, 
    selectCategoryById, 
    selectCategoryByName, 
} 

同時,在product/selector可以導入這兩個類別和產品選擇文件如下:

import { createSelector } from 'reselect'; 
import { selectCategoryById } from './category/selectors'; 

const productsSelector = state => state.products; 

const selectProductByCategoryId = id => { 
    return createSelector(
    productsSelector, 
    selectCategoryById, 
    (products, categories) => products.filter(p.category.indexOf(id) > -1) 
); 
} 

export default { 
    productsSelector, 
    selectProductByCategoryId, 
} 

而在product/reducer中,您可以導入兩個選擇器並根據類別邏輯返回新的已更改狀態。

+0

雖然我不能在我的產品減速器中訪問整個狀態嗎?我只能訪問產品狀態對象。 – NRaf

+0

嗯,對!所以在這種情況下,我認爲您可以在調用FETCH_ALL_PRODUCTS方法後立即在componentWillReceiveProps中執行組件上的過濾器邏輯(不確定這是否是最佳實踐)。或者,如果您可以通過添加過濾服務器端'GET''/products /:categoryId'的端點來訪問/維護後端。 –