首页 > 解决方案 > React JS通过按钮进行多重过滤

问题描述

我需要按类型过滤多个数组的帮助:收入或支出、上个月的交易以及价值超过 1000 的交易。我有按钮组件按钮:

<div className="buttons">
    {buttons.map(item => (
      <button
        variant="outline-primary"
        key={item.id}
        className={item.btnClass}
        type="button"
        onClick={() => {
          filterData(item.type, item.parameter, item.id);
        }}
      >
        {item.label}
      </button>

数据

transtactions = [{
id: 0,
value: 1000,
type: 'income',
date: new Date(2018, 1, 1)},
{
id: 1,
value: 500,
type: 'outlay',
date: new Date(2019, 1, 2)
},
{
id: 2,
value: 800,
type: 'income',
date: new Date(2019, 0, 3)
},
{
id: 3,
value: 2000,
type: 'outlay',
date: new Date(2019, 1, 4)
},
{
id: 4,
value: 1000,
type: 'income',
date: new Date(2019, 1, 4)
},
{
id: 5,
value: 999,
type: 'income',
date: new Date(2019, 1, 5)
},];

按钮

const buttons = [{
       id: 0,
       label: 'income',
       type: 'incomeFilter',
       parameter: 'income',
       btnClass: ''
      },
      {
      id: 1,
      label: 'outlay',
      type: 'outlayFilter',
      parameter: 'outlay',
      btnClass: ''
      },
      {
      id: 2,
      label: 'last month',
      type: 'date',
      parameter: '',
      btnClass: ''
      },
      {
      id: 3,
      label: 'more 1000',
      type: 'value',
      parameter: '1000',
      btnClass: ''
      }];

我想不出使用该函数过滤表的算法。我试图添加额外的数组,但一切都很笨拙

标签: javascriptreactjsbuttonfilter

解决方案


请试试这个::

filterData(type, param, id) {
    let temp = [];
    if (type == 'date') {
      let today = new Date();
      for (let t of transtactions) {
        if (t.date.getMonth() == today.getMonth()) {
          temp.push(t);
        }
      }
    } else if (type == 'value') {
      for (let t of transtactions) {
        if (t.value > 1000) {
          temp.push(t);
        }
      }
    }
    this.setState({
      filteredTransactions: temp
    });
  }

我也解决了你的问题。是完整的解决方案。


推荐阅读