如何用React中的JSON数据填充下拉列表?

时间:2018-02-22 11:25:42

标签: javascript reactjs api fetch-api

我尝试使用JSON格式的数据填写下拉列表,但现在下拉列表为空(未找到结果...)

我当然有一个错误,我无法理解我在哪里混淆。

我会附上我的API屏幕。

我想获得Station和NameStation ..

API for Stations

我的代码:

import React, { Component } from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

function parseStations(stations){
  return stations.map((station) => {
    return { label: station.NameStation, value: station.Station };
  });
}

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', {
      data: 'Station',
      data: 'NameStation',
      method: "GET"
    }).then(res => res.json())
      .then(res => this.setState({ stations: parseStations(res.stations) }))
      //.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.options}
            options={this.state.stations}
            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>
    );
  }
}

2 个答案:

答案 0 :(得分:3)

似乎你做了一个拼写错误,命名为道具stations而不是options

<Select
    onChange={this.onChange}
    options={this.state.stations} // here
    value={this.state.value}
    clearable={false}
/>

编辑:您需要首先解析您的json以传递正确的对象数组,如下所示:[{ label: nameStation, value: Station }]

编辑2:这是您的数据解析器:

function parseStations(stations){
  return stations.map((station) => {
    return { label: station.NameStation, value: station.Station };
  });
}

您可以在设置状态之前在异步请求中调用此方法:

.then(res => this.setState({ stations: parseStations(res.stations) }))

答案 1 :(得分:1)

  1. componentDidMount()仅在render()完成后执行。所以在你的UI被呈现时,没有办法getStations()被执行。 setState内部componentDidMount()因为触发重新渲染而不是一个好主意。请改用componentWillMount()

  2. 纠正Dyo提到的错字并使用options={this.state.stations}