【发布时间】:2020-07-08 12:26:27
【问题描述】:
我有一个从 Redux Store 收到的数据,还有我需要通过单击适当的类别按钮来过滤数据的类别。如何使用 Redux 实现过滤器? 数据库中的项目具有如下输出:
items = [{
id: 0
name: "example1"
price: 15
category: 0
},
{
id: 1
name: "example2"
price: 15
category: 1
}
]
类别有输出:
categories = ["one", "two"]
这是我的组件:
export default function Home() {
const itemData = useSelector((state) => state.main.items);
const loader = useSelector((state) => state.load.loading);
const [activeCategory, setActiveCategory] = useState(null);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchItems());
}, [dispatch]);
if (loader) {
return <Spinner />;
}
return (
<div className="container">
<div className="content__top">
<div className="categories">
<ul>
<li
className={activeCategory === null ? 'active' : ''}
onClick={() => setActiveCategory(null)}>
All
</li>
{categories &&
categories.map((category, index) => (
<li
key={index}
className={activeCategory === index ? 'active' : ''}
onMouseDown={() => dispatch(filterByCategory(itemData, category))}
onClick={() => setActiveCategory(index)}>
{category}
</li>
))}
</ul>
</div>
</div>
<h2 className="content__title">Items</h2>
<div className="content__items">
{itemData && itemData.map((item) => <Content key={item._id} {...item} />)}
</div>
</div>
);
}
这是我的行动:
export const FETCH_ITEMS = 'FETCH_ITEMS';
export const FILTER_BY_CATEGORY = 'FILTER_BY_CATEGORY';
export const fetchItems = () => {
return (dispatch) => {
dispatch(showLoader());
axios.get('http://localhost:4000/').then((response) => {
const items = response.data;
dispatch({
type: FETCH_ITEMS,
payload: items,
});
dispatch(hideLoader());
});
};
};
export const filterByCategory = (items, category) => {
return {
type: FILTER_BY_CATEGORY,
category,
// some kind of filter code
};
};
和减速器
const initialState = {
items: [],
};
export const fetchReducer = (state = initialState, action) => {
switch (action.type) {
case actions.FETCH_ITEMS:
return { ...state, items: action.payload };
case actions.FILTER_BY_CATEGORY:
return { ...state, filtered: action.category, category }; // Not sure about it
default:
return state;
}
};
【问题讨论】:
-
过滤后的数据是所有数据的计算结果,为什么不用选择器过滤呢?看起来您想在 store 中不必要地存储一个可以计算的计算值。
-
HMR,很好的提示。所以我需要首先使用选择器,然后 - 渲染项目?或者我可能需要使用重新选择库之类的东西?
-
我肯定会建议using reselect