DiscordJS v14动态StringSelectMenu创建问题求助
问题根源
你错误地将选项拼接成了字符串,但addOptions()方法需要接收的是符合格式的JavaScript对象数组,而非字符串内容。字符串无法被Discord.js的验证器解析为有效的选项对象,因此会提示缺少label和value必填属性。
另外代码里还有两处小问题:描述中的${name1}是未定义的变量,应该改为${name};value必须是字符串类型,你当前直接传入数字id,需要转成字符串。
修复后的代码
遍历数据库条目代码
console.log(result); if (result) { let string = ""; // 改为数组存储选项对象,而非字符串拼接 let selectOptions = []; for (entry in result) { const id = result[entry].id; const name = result[entry].name; const money1 = result[entry].money1; const money2 = result[entry].money2; const amount = result[entry].amount; string += `${name} (Item id = ${id}). The price is ${money1} Coin(s), ${money2} Diamond(s). There are ${amount} available of this item.\n\n`; // 向数组中推入符合要求的选项对象 selectOptions.push({ label: name, description: `Of the item ${name} with the id ${id} are ${amount} available. The price is ${money1} Coin(s), ${money2} Diamond(s).`, value: id.toString() // 强制转为字符串,符合select菜单的value类型要求 }); }
创建SelectMenu的代码
const select = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId("reward-buy") .setPlaceholder("Nothing selected") .addOptions(...selectOptions) // 用扩展运算符将数组元素作为独立参数传入 );
关键说明
addOptions()支持两种传参方式:多个独立的选项对象,或通过...扩展运算符传入对象数组。- 每个选项对象必须包含
label(菜单显示文本)、value(选中后返回的标识值,必须为字符串),description是可选的补充说明字段。 - 切勿用字符串拼接模拟对象结构,直接构建原生JavaScript对象才是Discord.js验证器能识别的格式。
内容的提问来源于stack exchange,提问作者JustinL
相关产品推荐
相关产品推荐

