问题描述
我是新来响应js的人,再次陷入了一个问题。我正在尝试从api调用加载下拉列表。尽管我可以从API获取数据并将其保存到状态,但是我无法使用它将其绑定到下拉列表。以下是我的代码来获取和绑定数据:
const initialState = {
venues: []
};
export default class AddLab extends Component {
constructor() {
super();
this.state = initialState;
this.getVenueList();
this.handleChange = this.handleChange.bind(this);
}
getVenueList() {
ApiService.getData(apiConfig.GET_VENUES,{}).then((res) => {
if (res.data && res.data.error == null) {
this.state.venues = res.data.result;
console.log(this.state.venues);
} else {
alert(res.data.error.description );
}
});
}
render() {
return (
<div className="card col-md-4">
<Row>
<Col>
<Form.Label>Venue</Form.Label>
<Form.Control as="select" componentclass="select" placeholder="Select venue" onChange={this.handleVenueChange}>
<option value="select">Select venue</option>
{
this.state.venues.map((venue) => {
return (<option value="s">{venue.venueName}</option>);
})
}
{/* <option value={apiConfig.ROLE_ADMIN}>Admin</option> */}
{/* <option value={apiConfig.ROLE_CLIENT}>Client</option> */}
</Form.Control>
<div style={{ fontSize: 12,color: "red" }}>
{this.state.projectIdError}
</div>
</Col>
</Row>
{this.state.isLoading ? (<div style={{
display: 'flex',justifyContent: 'center',alignItems: 'center',height: '100vh'
}}><div className="spinner-border text-primary" role="status" >
<span className="sr-only">Loading...</span>
</div></div>) : (<div></div>
)}
<div style={divStyle}>
<Button type="submit" name="submit" className="btn btn-primary mb-2">
Submit
</Button>
</div>
</div>
</Form>
</div>
);
}
}
我能够在getVenueList方法中从api获取数据,但是即使将其设置为state,下拉列表也不会更新。
解决方法
在getVenue方法设置状态中,您没有正确更新状态,如下所示:
this.setState({
venues: res.data.result
});