![](/img/trans.png)
[英]How to fill dropdown with json data from restful api using vanilla js
[英]How to get data from API in JSON format on ReactJS and Fill dropdown
我是客户区的新手,我想问一下从 API 获取数据的正确性如何。 我在 MVC.ASP.NET 上创建了一个 JSON 格式的 API,现在我想从 API 中获取两件事。
第一个是站号和他们的名字(它会附上一个截图)我想在这一点上取 Station 和 NameStation,并用这些数据填充我的下拉列表。
[Station 和 StationName API 屏幕][1]
我不确定我开始做的是否正确。
我的 API 的下一个数据点是 weatherData: (Date, Temp, Rain, WindSpeed, Snow, Apress)。
[天气数据API][2]
我只想将所有这些数据保存在一个数组中,然后在反应图中初始化它们,但现在我只想将它们保存在一个数组中。
这是我如何获取站数据并填写我的下拉列表的示例。
我的代码:
import React, { Component } from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
export default class Weather extends Component {
constructor(props) {
super(props);
this.state = {
options: [
{ value: true, label: 'Yes' },
{ value: false, label: 'No' }
], stations: [],
value: null
}
this.onChange = this.onChange.bind(this);
}
onChange(event) {
this.setState({ value: event.value });
console.log('Boolean Select value changed to', event.value);
}
componentDidMount() {
this.getStations();
}
getStations() {
fetch('http://localhost:56348/api/stations', {
method: "GET"
}).then(res => res.json())
.then(res => this.setState({ stations: res.stations }))
//.catch(e => )
}
render() {
return (
<div className="MasterSection">
<div className="wrapper">
<div className="section">Изберете № на станция</div>
<Select
onChange={this.onChange}
options={this.state.stations}
stations={this.state.value}
value={this.state.value}
clearable={false}
/>
</div>
<div class="section">
<input type="text" class="form-control" placeholder="Брой дни назад" aria-label="Username" aria-describedby="basic-addon1"></input>
</div>
<div class="section">
<button type="button" class="btn btn-outline-dark">Покажи</button>
</div>
</div>
);
}
}
我的下拉列表是空的:(
我有几个笔记。
1- 通常的做法是用大写字母而不是小字母来写你的班级。
2- 你在课堂上有几个错误(准确地说:重复)。
3- 您可以使用 fetch 函数从 API 获取数据。
4- 另请注意, react-native
和reactJs
是完全不同的。 React Native 用于在 Android 和 iOS 上构建原生移动应用程序。
使用 fetch 的示例
export default class Weather extends React.Component {
constructor(props) {
super(props);
this.state = {
stations: [],
options: [
{ value: true, label: 'Yes' },
{ value: false, label: 'No' }
],
value: null
};
}
componentDidMount() {
this.getStations();
}
getStations() {
fetch('API URL', {
method: "GET" // POST
}).then(res => res.json())
.then(res => this.setState({stations: res.stations}))
.catch(e => /* catch any errors here */)
}
render() {
return(
<View></View>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.