【问题标题】:How to fill dropdown with JSON data in React?如何在 React 中用 JSON 数据填充下拉列表?
【发布时间】:2018-08-02 05:39:40
【问题描述】:

我尝试使用 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>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs api fetch-api


    【解决方案1】:

    您似乎打错了命名道具 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) }))
    

    【讨论】:

    • @ZlatkaPijeva 将 parseStations 函数放在组件类之外或将其声明为方法(如果声明为方法,请删除“函数”)
    • 现在我只有两个错误: 第 19 行:'Station' is not defined no-undef 第 19 行:'NameStation' is not defined no-undef
    • @ZlatkaPijeva 您在初始状态下添加了[{ label: nameStation, value: Station }],我写这个只是为了说明您需要传递给 Select 选项的对象格式,只需删除它并将初始状态设置为空数组就像你以前一样:stations: [ ]
    • 我删除 [{ label: nameStation, value: Station }] 并留下空数组,但下拉列表仍然为空(未找到结果):(
    • @ZlatkaPijeva 可能将 res.stations 更改为 res.stations.Stations
    【解决方案2】:
    1. componentDidMount() 仅在 render() 完成后执行。所以getStations() 不可能在你的 UI 被渲染的时候被执行。将setState 放在componentDidMount() 中并不是一个好主意,因为它会触发重新渲染。请改用componentWillMount()

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

    【讨论】:

    • componentDidMount() 中获取数据是一个好习惯,您不能指望在使用componentWillMount() 进行第一次渲染之前获得数据,因此您还需要设置初始状态和重新渲染也会发生。 (也是componentWillMount will be deprecated in the future
    • @Dyo 我明白你的意思,我只关心setState。由于fetch() 本质上是异步的,因此也无法将它们分成两个不同的功能。你认为setState() 里面的componentDidMount() 可以吗?
    • 是的,当您在异步函数中设置状态时,对于同步操作,构造函数是更好的选择。
    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多