javascript - 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: ''
}];
我想不出使用该函数过滤表的算法。我试图添加额外的数组,但一切都很笨拙
解决方案
请试试这个::
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
});
}
我也解决了你的问题。这是完整的解决方案。
推荐阅读
- ssh - SSH 超时失败
- python - 登录页面上的 Django allauth 和 google recaptcha - 有什么好的解决方案吗?
- macos - 如何使用 Apple 脚本选择特定的应用程序窗口?
- reactjs - axios如何从圆括号内获取数据
- regex - bash 在下载页面上下载第一个匹配的正则表达式
- javascript - 串联继承具有相同签名的两个方法
- android - Android 将应用程序作为提要选项提供
- python - 如果大小取决于框架对象,如何获取应用程序尺寸?
- c# - 我可以在 .a 库中调试代码吗?
- html - Django/HTML - HTML 没有从上下文中显示完整的字符串,而只是其中的一部分