首页 > 解决方案 > 反应多选下拉

问题描述

尝试为 React-multi-select-dropdown 填充一系列选项

   this.state.users.map((user) => {
      if (!this.state.options.includes(user.badgeId))
        this.state.options.push({ name: user.badgeId, id: user._id });
      return this.state.options;
    });

在选项数组中获取多个相同的值。

    <Multiselect
      options={this.state.options} // Options to display in the dropdown
      //isObject={false}
      onSelect={this.onSelect} // Function will trigger on select event
      // onRemove={this.onRemove} // Function will trigger on remove event
      displayValue='name' // Property name to display in the dropdown options
    />

同样,一旦选择并提交表单,选定的 user.badgeId 将需要在其自己的数组中。

标签: javascriptarraysreactjs

解决方案


问题:您的代码检查该值user.badgeId是否不在数组中options。它总是返回 true,因为这样的数组填充了如下对象:{ name: user.badgeId, id: user._id }

一个简单的例子:

const myArray = [{a: 1, b:'banana'}, {a: 2, b:'banana'}]

myArray.includes(1) // false

相反,您可以使用.find()来获取数组中具有 .find() 的对象name === badgeId

find() 返回满足提供的测试函数的第一个元素的值。这将是undefined如果什么都没有找到。

现在我们可以在数组中搜索和元素,如果找到它就做一些事情。像这样:

const findResult = this.state.options.find((obj) => obj.name === user.badgeId);
if (typeof findResult === "undefined")
  // Do something

我对这些词不是很好,所以如果这令人困惑,请随时要求澄清。或者你可以看看这个答案是否有帮助


推荐阅读