如何在React中将JSON响应呈现为下拉列表 [英] How to render JSON response as dropdown list in React

查看:24
本文介绍了如何在React中将JSON响应呈现为下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试获取从API收到的一些JSON数据,并将其放入一个非常简单的Reaction应用程序的下拉列表中。

这是到目前为止我的下拉组件:

import React from 'react';

var values;

fetch('http://localhost:8080/values')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        values = json;
        console.log(values);
    });

class DropDown extends React.Component {
    render(){
        return <div className="drop-down">
            <p>I would like to render a dropdown here from the values object</p>
            </div>;
    }
}

export default DropDown;

任何My JSON如下所示:

{  
   "values":[  
      {  
         "id":0,
         "name":"Jeff"
      },
      {  
         "id":1,
         "name":"Joe"
      },
      {  
         "id":2,
         "name":"John"
      },
      {  
         "id":3,
         "name":"Billy"
      },
      {  
         "id":4,
         "name":"Horace"
      },
      {  
         "id":5,
         "name":"Greg"
      }
   ]
}
我希望下拉选项与每个元素的‘name’相对应,并希望‘id’在通过选择一个选项触发事件时用作元素标识符。如果您能就如何将此数据放入下拉列表以响应用户输入提供任何建议,我们将不胜感激。

推荐答案

调用您的Reaction组件的componentDidMount生命周期函数中的接口,然后保存状态中的响应,然后呈现选择下拉菜单

import React from 'react';

class DropDown extends React.Component {
    state = {
        values: []
    }
    componentDidMount() {
       fetch('http://localhost:8080/values')
        .then(function(res) {
            return res.json();
        }).then((json)=> {
            this.setState({
               values: json
            })
        });
    }
    render(){
        return <div className="drop-down">
            <p>I would like to render a dropdown here from the values object</p>
              <select>{
                 this.state.values.map((obj) => {
                     return <option value={obj.id}>{obj.name}</option>
                 })
              }</select>
            </div>;
    }
}

export default DropDown;

这篇关于如何在React中将JSON响应呈现为下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆