gpt4 book ai didi

javascript - 用于过滤内容 React 的开/关切换

转载 作者:行者123 更新时间:2023-11-30 11:51:55 24 4
gpt4 key购买 nike

此 React 代码根据其包含的“标签”过滤变量(如列表数组中所示)。

但是,我无法打开/关闭过滤器变量(标签)。

我希望能够打开/关闭某些过滤器,并且只应用这些过滤器。

这是如何实现的?

我的全部代码都在这个codepen中( http://codepen.io/yarnball/pen/GqbyWr?editors=1010 )

我相信我必须知道如何将它添加到第 79 行(下面)的数组中,但我没有成功

第 79 行:

selectTag: function (tag) {
this.setState({
displayedCategories: this.state.displayedCategories.concat([tag]),
$push : [newObject]
});
},

我的数据是这样的:

    "title": "Into the Wild",
"tag": [
{
"name": "Movie",
"taglevel": 1,
"id": 1
},
{
"name": "Adventure",
"taglevel": 2,
"id": 30
},
{
"name": "Book",
"taglevel": 1,
"id": 2
}
],
"info": []
}

最佳答案

为了切换过滤器,您需要检查现有 displayedCategories 中是否存在标签,查看标签数组,然后将其删除或添加到.

通常我更喜欢尝试函数式,这样赋值就不会造成混淆,所以我会使用主要是函数式的风格。


首先要检查标签是否存在,我们可以使用过滤器操作。

var filteredCategories = this.state.displayedCategories
.filter(function (existingTag) {
return existingTag.taglevel !== tag.taglevel ||
existingTag.id !== tag.id;
});

所以我们现在有一个标签列表,这些标签被过滤以仅包括那些与传递的标签不匹配的标签。我们可以检查过滤后的列表是否与旧列表大小相同,看看我们是否删除了一个。或者,我们可以用另一种方式进行过滤,看看是否需要使用 some 删除一个。

if (filteredCategories.length === this.state.displayedCategories.length){
// tag wasn't present, add it
} else {
// tag was present, use filtered list.
}

正如我上面所说,我更喜欢函数式,所以我们可以稍微改变一下:

var newCategories = filteredCategories.length === this.state.displayedCategories.length ?
filteredCategories.concat([tag]) :
filteredCategories;

然后我们需要设置状态:

this.setState({
displayedCategories: newCategories,
});

将它们组合在一起:

var filteredCategories = this.state.displayedCategories
.filter(function (existingTag) {
return existingTag.taglevel !== tag.taglevel ||
existingTag.id !== tag.id;
});

var newCategories = filteredCategories.length === this.state.displayedCategories.length ?
filteredCategories.concat([tag]) :
filteredCategories;

this.setState({
displayedCategories: newCategories,
});

关于javascript - 用于过滤内容 React 的开/关切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com