【问题标题】:Duplicating dropdown filter items from API - Reactjs从 API 复制下拉过滤器项 - Reactjs
【发布时间】:2019-12-14 00:41:39
【问题描述】:

我已经创建了我的下拉菜单,但不幸的是它从 API 收到了重复的值。我从 BE 收到一定数量的文件,其中一些具有相同的名称,因此在我的下拉列表中我收到了重复的名称。我的代码如下所示:

我的功能

divideItems = () => {

        let startIndex = ((parseInt(this.state.activePaginationTab) + 1) * this.state.rowsPerPage) - this.state.rowsPerPage;
        let endIndex = (parseInt(this.state.activePaginationTab) + 1) * this.state.rowsPerPage - 1;
        let tabItems = [];

        for (let i = startIndex; i <= endIndex; i++) {
            if (this.state.items[i]) {
                tabItems.push(this.state.items[i]);
            }
        }

        this.setState({
            tabItems: tabItems
        }, () => {

        });

我的渲染

<RBS.Dropdown>
     <RBS.Dropdown.Toggle  id="dropdown-invoice-header">
          {translations.type}
     </RBS.Dropdown.Toggle>

         <RBS.Dropdown.Menu>
              {this.state.tabItems.map(item => (
       <RBS.Dropdown.Item >{item.documentType}</RBS.Dropdown.Item>
))}
           </RBS.Dropdown.Menu>
      </RBS.Dropdown>

结果在我的下拉菜单中重复项目。

【问题讨论】:

  • state.tabItems 中是否也有重复条目?
  • 是的,因为它是一张桌子,我使用state.tabItems 也更进一步。

标签: javascript arrays reactjs api


【解决方案1】:

删除重复项

const uniqueItems = [];
tabItems.map(item => {
    if (uniqueItems.indexOf(item.documentType) === -1) {
        uniqueItems.push(item.documentType)
    }
});


this.setState({
    tabItems: uniqueItems 
}, () => {

【讨论】:

  • 箭头函数item=&gt;后没有值
【解决方案2】:

您可以在设置状态之前过滤掉重复项:

for (let i = startIndex; i <= endIndex; i++) {
    if (this.state.items[i] && tabItems.indexOf(this.state.items[i]) === -1) {
        tabItems.push(this.state.items[i]);
    }
}

【讨论】:

  • @PandaMastr 你能在for循环之后试试console.log(tabItems);看看它是否真的被过滤了
【解决方案3】:

您可以使用 ES6 中的 Setspread operator,因为 Set 不允许重复,如果找到,将从数组中删除:

uniqueItems = [...new Set(tabItems)];

或更短:

[new Set(tabItems)].map(item => { // do stuff });

或者你可以先做 .filter 然后再做 .map:

uniqueItems = tabItems.filter((item, index) { return a.indexOf(index) == index; });

【讨论】:

  • 是的,但我收到一个空数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 2023-01-14
  • 2023-03-14
  • 2010-12-24
  • 2020-05-10
相关资源
最近更新 更多