选择的选项无法呈现

时间:2017-02-18 00:03:45

标签: javascript reactjs axios

组件

import React from 'react';
import { getRegions } from '../helpers'

class RegionSelect extends React.Component {
  constructor(props) {
      super(props);
      this.state = { regions: [],
                     selectedRegion: ''
                   };

      this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    var self = this
    getRegions().then(val => {
      self.setState({regions:val});
    })
  }

  handleChange(event) {
    this.setState({selectedRegion: event.target.value});
  }

  renderRegionPickList() {
    console.log('regions');
    console.log(this.state.regions);
    this.state.regions.map((o) => {
      return (
        <option key={o.label} value={o.value}>{o.label}</option>
      )
    })
  }

  render() {
    return (
      <div className="slds-form-element">
        <svg aria-hidden="true" className="slds-icon slds-icon-text-default slds-icon--small slds-p-around--xx-small">
          <use xlinkHref={locationIcon}></use>
        </svg>
        <label className="slds-form-element__label">Region</label>
        <div className="slds-form-element__control">
          <div className="slds-select_container">
            <select className="slds-select" value={this.state.selectedRegion} onChange={this.handleChange}>
              <option value=''>--select a region--</option>
              {this.renderRegionPickList()}
            </select>
          </div>
        </div>
      </div>
    );
  }
}

export default RegionSelect;

辅助

import axios from 'axios'

export function getRegions() {

  return new Promise(function(resolve,reject){

  // make requst for select values
  var request = axios.get(`${REST_API_URL}sobjects/User/describe/`,
     API_TOKEN
   ).then(function (response){
      const region = response.data.fields.find(field => field.name === 'Region__c');
      return resolve(region.picklistValues);
   })
  })
}

页面

enter image description here

控制台

enter image description here

基于docs,我看不出这是怎么回事。我错过了生命周期方法的东西吗?当页面加载时,regions数组为空,然后componentDidMount()执行重新呈现并且它不再为空。

1 个答案:

答案 0 :(得分:1)

您只需要在map内返回renderRegionPickList的结果,就像目前一样,它会返回undefined

renderRegionPickList() {
  return this.state.regions.map((o) => (
    <option key={o.label} value={o.value}>
      {o.label}
    </option>
  ))
}