javascript - 反应多选下拉
问题描述
尝试为 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 将需要在其自己的数组中。
解决方案
问题:您的代码检查该值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
我对这些词不是很好,所以如果这令人困惑,请随时要求澄清。或者你可以看看这个答案是否有帮助
推荐阅读
- windows - WSUS Package Publisher 从属性中“杀死”引用
- r - 从带有条件的表中提取数据
- javascript - 内容安全策略阻止 script-src - React 应用程序
- snakemake - 输入文件中的 Snakemake-通配符无法从输出文件中确定
- mongodb - FilterDefinitionBuidler 忽略与字段的给定值匹配的文档
- python - 可以在 SageMaker(实验室 1.2.*)上使用 dask 仪表板吗?
- django - 在 Caddy 反向代理后面使用 Django 时的 ALLOWED_HOSTS
- java - 二分搜索算法不返回变量
- c# - 如果绑定到 int 和 datetime,“asp-disabled”对 nop-editor 不起作用
- html - 反应:使页脚位于底部