我是新来的反应者,希望实现加载3个下拉列表[Group,Service,Temp]的功能。类似地,第2个dropdown [Service]应基于第一个dropdown [group] onchange事件加载或绑定数据。第3个dropdown [temp]应基于第2个dropdown [Service] onchange事件绑定数据。
我将使用axios从api获取数据,并且json结果如下所示
尝试以下代码以加载数据
import React, { Component } from "react";
class Dropdown extends Component {
state = {
teams: [],
services: [],
selectedGroup: "",
selectedService: "",
validationError: ""
};
componentDidMount() {
fetch("https://testapiv1.azurewebsites.net/weatherforecast")
.then(response => {
return response.json();
//debugger;
})
.then(data => {
let teamsFromApi = data.map(team => {
return { value: team.Group, display: team.Group };
});
let SevicesFromApi = data.map(team => {
return { value: team.Service, display: team.Service };
});
this.setState({
teams: [
{ value: "", display: "(Select your Group)" }
].concat(teamsFromApi),
services: [
{ value: "", display: "(Select your Service)" }
].concat(SevicesFromApi)
});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
<select
value={this.state.selectedGroup}
onChange={e =>
this.setState({
selectedGroup: e.target.value,
validationError:
e.target.value === ""
? "You must select your Group"
: ""
})
}
>
{this.state.teams.map(team => (
<option key={team.value} value={team.value}>
{team.display}
</option>
))}
</select>
<select
value={this.state.selectedService}
onChange={e =>
this.setState({
selectedService: e.target.value,
validationError:
e.target.value === ""
? "You must select your Service"
: ""
})
}
>
{this.state.services.map(team => (
<option key={team.value} value={team.value}>
{team.display}
</option>
))}
</select>
<div style={{ color: "red", marginTop: "5px" }}>
{this.state.validationError}
</div>
</div>
);
}
}
谁能指导我如何实现在React中加载这3个下拉列表的功能。
我们非常感谢您的帮助!
谢谢