首页 > 解决方案 > 从列表数组中附加一个值 - 反应原生

问题描述

这个API要求我发送一些逗号分隔的数据,在处理用户输入时我使用这样的复选框

   <SelectMultiple
      items={dairy}
      selectedItems={this.state.selectedIngredients}
      onSelectionsChange={this.onSelectionsChange} />

如果我在 FlatList 上呈现 selectedIngredients(使用 item.value),我绝对可以看到输入,但是当我尝试打印我正在使用的实际 url 时,我得到了这个 [object,Object]

this.state.selectedIngredients在视图中使用,结果如下:

url.com/api/?=[对象对象],[对象对象],[对象对象]

在我的search函数中,我使用该代码来处理用户输入:

  const { selectedIngredients } = this.state;
  let url = "url.com/api/?i=" + selectedIngredients

在图书馆的文档中,他们说所选项目是字符串类型数组或 { label, value } 我使用那里提供的方法来附加所选项目:

  onSelectionsChange = (selectedIngredients) => {
    // selectedFruits is array of { label, value }
    this.setState({ selectedIngredients})
  }

我尝试添加.value它们并没有解决我的问题。有人可以帮忙吗?

控制台记录 this.state.selectedIngredients:

Array [
  Object {
    "label": "Goat cheese",
    "value": "Goat cheese",
  },
  Object {
    "label": "Cream cheese",
    "value": "Cream cheese",
  },
  Object {
    "label": "Butter",
    "value": "Butter",
  },
]

标签: javascriptreactjsreact-nativejsx

解决方案


selectedIngredients = [
 {
    "label": "Goat cheese",
    "value": "Goat cheese",
  },
  {
    "label": "Cream cheese",
    "value": "Cream cheese",
  },
  {
   "label": "Butter",
    "value": "Butter",
  },
]

let selectedValues = selectedIngredients.map((ingredient)=> ingredient.value)
let selectedValuesInString = selectedValues.join(',');
console.log(selectedValuesInString)


推荐阅读