[英]Redux helper function to check if a value is in the store
我有一個過濾器面板,用戶可以在其中 select 不同的顏色過濾器:
// ColorButton.jsx
function ColorButton({ color }) {
const handleFilterSelected = ({ id }) => {
dispatch(applyFilter({ type: "colors", value: id }));
};
return (
<div className="color-button" onClick={() => handleFilterSelected(color)}>
{isFilterSelected({ type: "colors", value: color.id }) ? "yay" : "nay"}
</div>
);
}
選定的過濾器存儲在 redux 存儲中, isFilterSelect
function 如下所示:
// redux/utils/filter.utils.js
export const isFilterSelected = ({ type, value }) => {
const {
filters: { applied }
} = store.getState();
return applied
.filter((f) => f.type === type)
.map((f) => f.value)
.includes(value);
};
問題是在將選定過濾器添加到applied
數組之前運行檢查。
作為一個更普遍的問題 - 擁有依賴於 redux 商店的“幫助”功能甚至是一個好主意嗎?
您的助手 function 應該寫為獲取當前 state 的選擇器,並且您應該手動使用useSelector
而不是store.getState
,因為這將在選擇器值更改時更新您的組件。
function ColorButton({ color }) {
const isSelected = useSelector(state => isFilterSelected(state, { type: "colors", value: color.id }));
return (
<div className="color-button">
{isSelected ? "yay" : "nay"}
</div>
);
}
// redux/utils/filter.utils.js
export const isFilterSelected = (state, { type, value }) => {
return state.filters.applied
.filter((f) => f.type === type)
.map((f) => f.value)
.includes(value);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.