我目前正在尝试从API中获取一些JSON数据,并将其放入一个非常简单的React应用程序的下拉列表中。
到目前为止,这是我的DropDown组件:
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;
我的任何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"
}
]
}
我希望下拉选项对应于每个元素的“名称”,并且当通过选择选项触发事件时,'id'将用作元素标识符。关于将这些数据输入到响应用户输入的下拉列表的任何建议都将非常感激。
你可以这样做:
import React from 'react';
var values;
class DropDown extends React.Component {
constructor(){
super();
this.state = {
options: []
}
}
componentDidMount(){
this.fetchOptions()
}
fetchOptions(){
fetch('http://localhost:8080/values')
.then((res) => {
return res.json();
}).then((json) => {
values = json;
this.setState({options: values.values})
console.log(values);
});
}
render(){
return <div className="drop-down">
<select>
{ this.state.options.map((option, key) => <option key={key} >{option}</option>) }
</select>
</div>;
}
}
export default DropDown;
基本上你正在初始化状态并将options
设置为null。
然后,当组件安装在浏览器中时,您将获取选项。使用this.setState()
将这些值设置为您的状态。
注意:在componentDidMount()
而不是componentWillMount()
中进行任何API调用非常重要。如果你在componentWillMount()
中调用它,请求将被提出两次。
然后通过在渲染函数中映射它们来渲染这些选项
在React组件的componentDidMount
生命周期函数中调用API,然后将响应保存在状态中,然后呈现Select下拉列表
import React from 'react';
class DropDown extends React.Component {
state = {
values: []
}
componentDidMount() {
fetch('http://localhost:8080/values')
.then(function(res) {
return res.json();
}).then(function(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;