如何将 select 中的数据推送到单个数组中?

how to push the data from a select in a single array?

我正在使用 react-select,我的 api 希望我发送这样的字符串数组 ["purple","red" , "orange"] 但 react-select 给了我一个对象数组,所以我所做的是通过 newValue 映射选择每个值并放入一个 vaiable 数组,但我得到分隔数组中的每个值,如 ["purple"]、["red"]、["orange"]

handleChange = (newValue: any, actionMeta: any) => {
console.log("newValue-->",newValue);
newValue.map((obj: any) => {
  const array = [];
  array.push(obj.value);
  console.log("array-->",array);
});

完整代码: https://codesandbox.io/s/react-codesandboxer-example-sf7tz?file=/example.js

在映射之前在外部初始化你的数组。

否则您将为每个对象创建新数组。

 const array = [];
 newValue.map((obj: any) => {  
  array.push(obj.value);
  console.log("array-->",array);
});

根据 react select 文档,它应该是具有值和标签的对象数组。所以在您的情况下,您可以按照以下方式进行操作。

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

let input = ["purple", "red", "orange"] 

let output = input.map(item => ({value: item, label: capitalizeFirstLetter(item) }))

console.log(output)

问题片段的解释

newValue.map((obj: any) => {
  const array = [];
  array.push(obj.value);
  console.log("array-->",array);
});

这里是通过每个对象进行映射,然后每次映射时都会创建一个空数组,将值推送到该数组并打印它。

所以以第一项为例,红色迭代->创建空数组->将红色值推入空数组,然后打印。

所以循环3次,因为数组的长度是3,所以循环3次就得到了数组。

修复问题片段是在循环外声明数组并按照文档建议的方式推送,然后您可以将 select 组件作为选项传递给 react select 组件,它将按预期工作。