【问题标题】:How to map an array from response API to select element in react?如何将响应 API 中的数组映射到响应中的选择元素?
【发布时间】:2020-06-17 22:17:50
【问题描述】:

我正在尝试将数组中的数据放入反应中。我首先从 api 响应中检索数组并存储在 state 中。下面是我的代码,它未能获得价值,但关键是<select>

temp_list = [
            0:{fruit:"apple"},
            1:{fruit:"orange"}]

const f_list = this.state.fruit
const tmp_list = Object.keys(f_list).map((item, index) => <option value={item.fruit} >{item.fruit}</option>);

&lt;select&gt; option 的结果将是:

0
1

预期:

apple
orange

我怎样才能实现我想要的?谢谢

【问题讨论】:

  • 您在标题中输入了react-select。我可以假设您指的是反应环境中的select 元素,而不是react-select library
  • 你的数据结构不正确temp_list 可能像[ {fruit:"apple"}, {fruit:"orange"}]
  • @George 是的,我指的是选择元素。已经修改了标题。感谢您的提醒
  • @ManjeetThakur 我在控制台打印的数据与上面相同。如果数组和你的一样,我的代码怎么改?

标签: arrays reactjs select axios map-function


【解决方案1】:

如果您确定f_listobject。那你应该试试这个,

const tmp_list = Object.keys(f_list).map((item, index) => <option value={f_list[item].fruit} >{f_list[item].fruit}</option>);

Demo

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2017-04-19
    • 2019-09-30
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 2014-04-12
    相关资源
    最近更新 更多