如何使用React在浏览器中显示控制台应用程序?

时间:2017-10-14 15:56:45

标签: javascript node.js reactjs react-router

我为一门课程制作了一个简单的天气应用程序,我希望它能在浏览器中显示。现在,该应用程序仅适用于控制台。我用React做了一个非常简单的前端,我无法弄清楚如何将两者结合起来。

这是天气应用程序:

const yargs = require('yargs');
const axios = require('axios');

const argv = yargs
  .options({
    a: {
      demand: true,
      alias: 'address',
      describe: 'Address to fetch weather for',
      string: true
    }
})
.help()
.alias('help', 'h')
.argv;

var encodedAddress = encodeURIComponent(argv.address);
var geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?
address=${encodedAddress}`;

axios.get(geocodeUrl).then((response) => {
    if(response.data.status === 'ZERO_RESULTS'){
        throw new Error('Unable to find that address.');
    }

    var lat = response.data.results[0].geometry.location.lat;
    var lng = response.data.results[0].geometry.location.lng;
    var weatherUrl = `https://api.darksky.net/forecast/c19cc88150a85b69753b7fc23e3ca99d/${lat},${lng}`;

    console.log(response.data.results[0].formatted_address);
    return axios.get(weatherUrl);
}).then((response) => {
    var temperature = response.data.currently.temperature;
    var apparentTemperature = response.data.currently.apparentTemperature;
    console.log(`It's currently ${temperature}. It feels like 
${apparentTemperature}`);
}).catch((e) => {
    if(e.code === 'ENOTFOUND'){
        console.log('Unable to connect to API servers.');
    } else {
        console.log(e.message);
    }
});

所以,我几乎只是创建了一个带有文本框的基本表单来输入位置和提交按钮。如何让它搜索纬度/经度,找到天气,并在屏幕上显示?

这是React页面,它非常简单,当我弄清楚如何显示我想要的内容时,我当然会加入:

import React, { Component } from 'react';

class Homepage extends Component {
  render() {
   return (
    <div className="container-fluid">

        <h1>
            Weather
        </h1>
        <form action="/weather">
            <div id="address" className="form-group">
                <input className="form-control" type="text" name="address" placeholder="Location" />
            </div>
            <div id="address" className="form-group">
                <button className="btn btn-lg btn-primary btn-block">Search!</button>
            </div>
        </form>
    </div>
    );
  }
}


export default Homepage;

1 个答案:

答案 0 :(得分:0)

为了简单起见,我已将API调用直接移到组件中,但在实际项目中,您希望将它们分开并导入它们。

我还添加了一个非常简单的div来显示搜索结果(只有它完全成功)。如果有效,请告诉我,如果您有任何问题。

import React, { Component } from 'react';
import axios from 'axios';

class Homepage extends Component {
  // constructor to initialize state
  contructor(props) {
    super(props);
    this.state = {
      address: '',
      temperature: '',
      apparentTemperature: '',
      lat: '',
      lng: ''
    }
  }
  // handler for 'address' controlled input
  onChangeAddress = (e) => {
    this.setState({ address: e.target.value });
  }
  // execute search
  doSearch = (e) => {
    e.preventDefault();
    const encodedAddress = encodeURIComponent(this.state.address);
    const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`;

    axios.get(geocodeUrl).then((response) => {
      if(response.data.status === 'ZERO_RESULTS'){
        throw new Error('Unable to find that address.');
      }
      this.setState({
        lat: response.data.results[0].geometry.location.lat,
        lng: response.data.results[0].geometry.location.lng
      });
      const weatherUrl = `https://api.darksky.net/forecast/c19cc88150a85b69753b7fc23e3ca99d/${this.state.lat},${this.state.lng}`;

      console.log(response.data.results[0].formatted_address);
      return axios.get(weatherUrl);
    }).then((response) => {
      this.setState({
        temperature: response.data.currently.temperature,
        apparentTemperature: response.data.currently.apparentTemperature
      });
      console.log(`It's currently ${this.state.temperature}. It feels like ${this.state.apparentTemperature}`);
    }).catch((e) => {
      if(e.code === 'ENOTFOUND'){
        console.log('Unable to connect to API servers.');
      } else {
        console.log(e.message);
      }
    });
  }
  render() {
    const { lat, lng, address, temperature, apparentTemperature } = this.state;
    return (
      <div className="container-fluid">
        <h1>
          Weather
        </h1>
//        { lat !== '' && lng !== '' && temperature !== '' && apparentTemperature !== '' &&
          <div className="weather-info">
            address: {address}<br />
            latitude: {lat}<br />
            longitude: {lng}<br />
            temperature: {temperature}<br />
            feels like: {apparentTemperature}
          </div>
//        }
        <form>
          <div id="address" className="form-group">
            <input className="form-control" type="text" name="address" placeholder="Location" value={address} onChange={this.onChangeAddress} />
          </div>
          <div id="address" className="form-group">
            <button className="btn btn-lg btn-primary btn-block" onClick={this.doSearch}>Search!</button>
          </div>
        </form>
      </div>
    );
  }
}

export default Homepage;