我正在尝试正确构建对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

最佳答案

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

/**
 * 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} />;
    }
}

10-07 19:41