【问题标题】:What is the best practice to remove duplicate items from an array in a reducer?从减速器中的数组中删除重复项的最佳做法是什么?
【发布时间】:2020-04-08 10:25:16
【问题描述】:

我是使用 reducer 存储数据的新手,并且偶然发现了一个问题。我目前有一个复选框列表,当单击这些复选框时,它会调度一个动作以将它们存储在我的减速器的数组中。但是,目前,我可以继续检查/取消检查,并且将继续将相同的值推送到数组中。

如何防止这种情况发生?我是否以某种方式在减速器内部或复选框上的 handleChange 事件中过滤掉?

我添加了我当前代码的一个小sn-p

谢谢!

function handleCheckboxChange(e) {
    if (e.target.checked) {
      checkboxContext.dispatch({
        type: 'SET_PROPERTY_TYPE',
        payload: { [e.target.name]: e.target.checked }
      });
    }
  }
  
  
 const FilterCheckbox = ({ name, value, handleChange, checkedItems }) => (
  <Label>
    <FilterInput
      type="checkbox"
      name={name}
      value={value}
      onChange={handleChange}
      checked={checkedItems[name]}
    />
    {name}
  </Label>
);

export default FilterCheckbox;

// Sets the selected value...
 case 'SET_PROPERTY_TYPE':
      return {
        ...state,
        propertyType: [...state.propertyType, action.payload]
      };

【问题讨论】:

    标签: reactjs react-redux reducers react-context


    【解决方案1】:

    是的,您可以过滤您的 state.propertyType 以删除任何重复项。

    // Sets the selected value...
     case 'SET_PROPERTY_TYPE':
          return {
            ...state,
            propertyType: [
                ...state.propertyType.filter((value) => 
                     Object.keys(value)[0] !== Object.keys(action.payload)[0]), 
                action.payload
            ]
          };
    

    您还可以将您的 state.propertyType 更改为一个对象以使事情变得更好:

      function handleCheckboxChange(e) {
        checkboxContext.dispatch({
          type: 'SET_PROPERTY_TYPE',
          payload: { [e.target.name]: e.target.checked }
        });
      }
    
    
     const FilterCheckbox = ({ name, value, handleChange, checkedItems }) => (
      <Label>
        <FilterInput
          type="checkbox"
          name={name}
          value={value}
          onChange={handleChange}
          checked={checkedItems[name]}
        />
        {name}
      </Label>
    );
    
    export default FilterCheckbox;
    
    // Sets the selected value...
     case 'SET_PROPERTY_TYPE':
          return {
            ...state,
            propertyType: {
              ...state.propertyType, 
              ...action.payload
            }
          };
    
    

    您还需要更改 FilterCheckbox 从状态映射的方式。

    【讨论】:

    • 太棒了!您也可以将state.propertyType 更改为对象,这样代码会更简洁一些,不需要过滤
    • 我刚刚注意到我还需要过滤掉未选中的值,因为我只是在 (e.target.checked) 上运行调度,如果我将它更改为一个对象,这行不通 - 会吗?
    • 我将添加一个以 state.propertyType 为对象的示例
    • 但这不会保持您单击复选框的顺序,这可能不适合您的需求。
    • 感谢您的帮助 Adam,为什么我需要更改它的映射方式?对不起,我对这一切都很陌生!
    猜你喜欢
    • 1970-01-01
    • 2010-09-26
    • 2019-09-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多