如何调用 API?

问题描述

我该如何解决这个问题?

import React from 'react';

function Form() {
    function callWeatherAPI(city) {
        let url = `api.openweathermap.org/data/2.5/weather?q=${city},&appid=3921214e64bf19a2ed23b79c5b270300`;
    }


    function submitForm() {
        // debugger;

        let city = document.forms["myForm"]["city"].value;
        let isValid = validateForm(city);
        if (isValid) {
            // call api
            callWeatherAPI(city);
        } else {
            alert("Please put in value for city");
        }
    }


    function validateForm(city) {
        if (city === "") {
            return false;
        } else {
            return true;
        }
        // return (city === "") ? false : true;
    }


    return ( <
        form name = "myForm"
        onSubmit = {
            submitForm
        } >
        <
        label > City: < /label> <
        input type = "text"
        name = "city" > < /input> <
        input type = "submit" > < /input>   <
        /form>

    );

}


export default Form;

解决方法

您需要从该端点获取数据,使用 fetch 和以下方法可能会有所帮助:

function Form(){
  const [targetValue,setTargetValue] = useState('');

  async function callWeatherAPI(city){
    const response = await fetch(`endpoint/${city}`);
    return await response.json(); // You will probably receive an object,get the value you want and return it here
  }

  async function submitForm() {
    // You should get the form value using reactivity..
    const city = document.forms["myForm"]["city"].value;
    const isValid = validateForm(city);
    if (isValid) {
      const response = await callWeatherAPI(city);
      setTargetValue(response);
    } else {
      alert("Please put in value for city");
    }
  }

  return (
    <form name="myForm" onSubmit={submitForm}>
      <label>City:</label>
      <input type="text" name="city"></input>
      <input type="submit"></input>
      <p>Response: {targetValue}</p>
    </form>
  );
}