Hom*_*ata 6 json reactjs dropdown
我目前正在尝试获取一些我从 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;
Run Code Online (Sandbox Code Playgroud)
任何我的 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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我希望下拉选项与每个元素的“名称”相对应,并且在通过选择选项触发事件时将“id”用作元素标识符。任何有关将此数据放入响应用户输入的下拉列表的建议将不胜感激。
在componentDidMountReact 组件的生命周期函数中调用 API,然后将响应保存在 state 中,然后呈现 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((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;
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
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;
Run Code Online (Sandbox Code Playgroud)
基本上你正在初始化状态并设置options为空。
然后,当组件安装在浏览器中时,您可以获取选项。这些值通过 来设置为您所在的州this.setState()。
componentDidMount()注意:在和 中进行任何 API 调用都很重要componentWillMount()。componentWillMount()如果您在请求中调用它,则会发出两次请求。
然后通过将这些选项映射到渲染函数中来渲染它们