根据条件计算项目 [英] Count items based on condition

查看:32
本文介绍了根据条件计算项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

商店的初始状态为:

let initialState = {
  items: [],
  itemsCount: 0,
  completedCount: 0
};

当我发送一个类型为 ADD_ITEM 的操作时,新项目被添加到 items 数组并且 itemsCount 递增(虽然我我不确定我是否做对了)

When I dispatch an action with the type ADD_ITEM the new item is added to the items array and itemsCount is incremented (Although I'm not sure if I'm doing it correctly)

case "ADD_ITEM": {
  return {
    ...state,
    items: [
      ...state.items,
      {
        title: action.name,
        dateCreated: action.date,
        id: action.id,
        isChecked: false
      }
    ],
    itemsCount: state.items.length + 1
  };
}

TOGGLE_ITEM

case "TOGGLE_ITEM": {
  return Object.assign({}, state, {
    items: state.items.map(item => {
      if (item.id !== action.id) {
        return item;
      }
      return Object.assign({}, item, {
        isChecked: !item.isChecked
      });
    })
  });
}

当我分派 REMOVE_ITEM 类型的操作时,将执行以下操作:

When I dispatch an action with the type REMOVE_ITEM the following is executed:

case "REMOVE_ITEM": {
  return Object.assign({}, state, {
    items: [...state.items.filter(item => item.id !== action.id)],
    itemsCount: state.items.length - 1
  });
}

现在我正在尝试计算 isCheckedtrue

Now I'm trying to count the items that have isChecked is true

state.items.map(item => {
    if(item.isChecked){
        //Increment count
    }
})

我不确定具体在哪里做.

I'm not sure where exactly to do that.

TOGGLE_ITEM 操作中?

在新的 COUNT_ITEM 操作中?如果是这样,该操作何时分派?

Inside a new COUNT_ITEM action? if so, when is that action dispatched?

如何为状态的一部分分配一个递增的数字?

And how do assign an incremented digit to part of the state?

推荐答案

你可以在你的动作/组件等需要它时计算它:

You can just compute it when you need it in your actions/components etc:

items.filter(item => item.isChecked).length

在您的状态中存储诸如某些项目的计数(包括 itemsCount 变量)之类的派生值不是一个好习惯(原因类似于您对状态进行标准化的原因).

It's not a good practice to store derived values such as the count of certain items (including the itemsCount variable) in your state (reasons similar to why you normalise your state).

如果您担心性能(它是 O(n),所以一般来说问题不大),您可以使用 记忆库.

If you are worried about performance (it's O(n) so shouldn't be much of an issue in general), you can use a memoization library.

这篇关于根据条件计算项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆