我应该使用事件监听器还是应该在React中使用生命周期方法?

时间:2018-06-06 13:35:10

标签: javascript reactjs javascript-events react-lifecycle

我有一个呈现表单的组件。这种形式可以吐回一组预定机场之间的距离。

{
  JFK: { LAX: 2475, LAS: 2248, PDX: 2454 },
  LAX: { JFK: 2475, LAS: 236, PDX: 834 },
  LAS: { JFK: 2248, LAX: 236, PDX: 763 },
  PDX: { JFK: 2454, LAS: 763, LAX: 834 },
}

此对象表示我将在API中获取的数据。

表单包含两个select / option下拉列表。一个代表起点,另一个代表终点。

enter image description here 我将所有相关代码放在一个名为handleSumbit的函数中,该函数应触发我正在导入的函数,该函数将输出所选机场之间的距离。

handleSubmit(e) {
    e.preventDefault();

    function returnAirPort(airport) {
      return airport;
    }

    var starting = document.getElementById('starting'),
        destination = document.getElementById('destination'),
        startingEventVal,
        destinationEventVal;

    starting.addEventListener('change', function(e) {
      startingEventVal = returnAirPort(e.srcElement.value);
      console.log('startingEventVal', startingEventVal);
    });

    destination.addEventListener('change', function(e) {
      destinationEventVal = returnAirPort(e.srcElement.value);
      console.log('destinationEventVal', destinationEventVal);
    });

    (function(startingEventVal, destinationEventVal) {
      var distance = IntentMedia.Distances.distance_between_airports(startingEventVal, destinationEventVal);
      console.log("distance", distance);

      document.getElementById('feedback').innterHTML = distance
    })(startingEventVal, destinationEventVal);
  }

现在,我进入控制台的所有内容都是-1;如果无法确定距离或您进入无效机场,将获得的价值?!我不应该至少在DOM中获得那些渲染吗?

这是表格:

      <form onSubmit={this.handleSubmit}>
        {console.log(airportNames)}
        <div className="row">
          <div className="twelve columns">
            <h2>The following are our available flights</h2>
            <p>
              If your airport exists in the following dropdown we can supply the distance in miles or Kilometers below
              between them.
            </p>

            <label htmlFor="exampleEmailInput">Your Starting Airport</label>
            <select id="starting" className="u-full-width">
              <option defaultValue> -- select an option -- </option>
              {airportNames}
            </select>
          </div>
          <div className="twelve columns">
            <label htmlFor="exampleEmailInput">Your destination</label>
            <select id="destination" className="u-full-width">
              <option defaultValue> -- select an option -- </option>

              {airportNames}
            </select>
          </div>
        </div>
        <p id="feedback" />
        <button>Submit</button>
      </form>

所以我的问题是如何向DOM渲染选定机场之间的距离?

提前致谢!

0 个答案:

没有答案