简体   繁体   English

Redux helper function 检查值是否在商店中

[英]Redux helper function to check if a value is in the store

I have a filter panel where the user can select different color filters:我有一个过滤器面板,用户可以在其中 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>
  );
}

The selected filters are stored in the redux store and the isFilterSelect function looks like this:选定的过滤器存储在 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);
};

The issue is that the check runs before a selected filter is added to the applied array.问题是在将选定过滤器添加到applied数组之前运行检查。

As a more general question - is it even a good idea to have "helper" functions that depend on the redux store?作为一个更普遍的问题 - 拥有依赖于 redux 商店的“帮助”功能甚至是一个好主意吗?

Your helper function there should be written as a selector that gets the current state, and you should be using useSelector instead of store.getState manually, as that will update your component when the selector value changes.您的助手 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM