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

标签 javascript reactjs

此 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/

相关文章:

Apache Web 服务器不允许我刷新 on/about,但在 localhost 上它工作正常

javascript - node.js 标准模块的全局变量?

javascript - Mongoose Async 查找所有内容并更新每个内容

reactjs - react 。当在组件函数中导入函数时,我能知道为什么它不起作用 hooks setState..?

javascript - 如何将 Prop (状态和功能)传递给子路由器组件

reactjs - 我不断收到“'Object is of type ' 未知”错误

javascript - 使 Canvas 中的白色像素透明?

javascript - 解决未捕获的语法错误 : Unexpected token >

javascript - 如何从字符串中删除斜杠(\\)

javascript - 在 native react 中获取类型错误 undefined object ?