如何构造我的API调用,以及将密钥和查询放在何处?

时间:2019-05-30 21:20:05

标签: javascript reactjs api preventdefault

我正在尝试正确构建对openweatherapi的API调用,只是试图创建一个简单的气象应用程序,在该应用程序中,当用户输入城市时,天气预报就会呈现到页面上。到目前为止,这就是我所要做的,同时还尝试防止在按下按钮时刷新页面的默认操作。我正在使用反应。

class App extends Component {
  getWeatherData = (userInput, event) => {
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });
  };

./表格。 js如下

class Form extends Component {
  render() {
    return (
      <div>
        <form onSubmit={(this.props.getWeather, e)}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}

错误:

./src/Form.js
  Line 7:  'e' is not defined  no-undef

2 个答案:

答案 0 :(得分:1)

使用类组件,我会做这样的事情:
(每个类/函数应拆分为不同的文件)

/**
 * This is just a helper to encapsulate the weather fetching logic
 */
function getWeatherFromInput({ city, country }) {
    const query = `${city},${country}`;

    return axios({
        method: 'GET',
        url: `http://openweathermap.org/data/2.5/weather?${query}`,
        responseType: 'json'
    });
}

/**
 * Here is the specific form
 */
export class WeatherForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            city: '',
            country: ''
        };
    }

    handleSubmit = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state);
    };

    handleInputChange = (event) => {
        const { name, value } = event.target;
        this.setState({ [name]: value });
    };

    render() {
        const { city, country } = this.state;
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type='text'
                    name='city'
                    value={city}
                    onChange={this.handleInputChange}
                    placeholder='City...'
                />
                <input
                    type='text'
                    name='country'
                    value={country}
                    onChange={this.handleInputChange}
                    placeholder='Country'
                />
                <button type='submit'>Get weather</button>
            </form>
        );
    }
}

/**
 * And how you use it in your App
 */
export class App extends React.Component {
    constructor() {
        this.state = {
            weather: {}
        };
    }

    /**
     * The userInput is provided by the WeatherForm
     */
    handleSubmit = (userInput) => {
        getWeatherFromInput(userInput).then((response) => {
            this.setState({ weather: response.data });
        });
    };

    render() {
        return <WeatherForm onSubmit={handleSubmit} />;
    }
}

答案 1 :(得分:0)

您只需将表单移至您的应用程序类,就可以在组件之间传递表单数据,从而完美地完成了反应。

class App extends Component {
  getWeatherData = (event) => {
    const userInput = {
             event.target.city.value,
             event.target.country.value
       }
    event.preventDefault();
    axios({
      url: "http://openweathermap.org/data/2.5/weather/",
      method: "GET",
      dataType: "json",
      data: {
        q: userInput,
        API_KEY: "d108038ec889cfe762230283abaa7c7b"
      }
    }).then(res => {
      console.log(res);
      this.setState({});
    });


  render() {
    return (
      <div>
        <form onSubmit={this.getWeatherData}>
          <input type="text" name="city" placeholder="City..." />
          <input type="text" name="country" placeholder="Country" />
          <button>Get Weather</button>

        </form>
      </div>
    );
  }
}

您还不需要将userInput指定为可以通过使用event关键字访问值的函数内部设置的参数。