如何在API调用中将输入值作为参数传递?

问题描述 投票:0回答:1

如何在API调用中将输入值作为参数传递。我希望该应用的运行方式类似于将城市名称放置在输入字段中,然后输入提交按钮以获取所有天气数据。我检查了天气数据即将到来并保持状态。但我不知道如何获取输入的城市名称和通行证。如果您能帮助我,我将不胜感激。

//Action Creator ..

import weatherAPI from "../apis/weatherAPI";

export const fetchWeather = cityName => async dispatch => {
  const API_KEY = "240ef553958220e0d857212bc790cd14";

  const response = await weatherAPI.get(
    `/data/2.5/weather?q=${cityName}&appid=${API_KEY}`
  );
  dispatch({
    type: "FETCH_WEATHERLIST",
    payload: response.data
  });
};


//Reducer..
export default (state = [], action) => {
  if (action.type === "FETCH_WEATHERLIST") {
    return action.payload;
  }
  return {
    ...state
  };
};

//CombineRducer file..
import { combineReducers } from "redux";
import weatherListReducer from "./weatherListReducer";

export const rootReducer = combineReducers({
  weatherList: weatherListReducer
});
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchWeather } from "../actions";
class SearchBar extends Component {
  componentDidMount() {
    this.props.fetchWeather();
  }

  onChangeHandler(e) {}
  onSubmitHandler(e) {
    e.preventDefault();
  }
  render() {
    console.log(this.props.list.main);

    return (
      <div className="row container">
        <h4 className="blue-text">Weather App</h4>
        <form className="col s12" onSubmit={this.onSubmitHandler}>
          <div className="input-field">
            <input type="text" id="searchbar" />
            <label htmlFor="searchbar">Search City For Weather Forecast</label>
          </div>
          <div className="input-field ">
            <button className="btn " onChange={this.onChangeHandler}>
              Search City
            </button>
          </div>
        </form>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    list: state.weatherList
  };
};

export default connect(mapStateToProps, { fetchWeather })(SearchBar);
reactjs redux react-redux react-router redux-thunk
1个回答
0
投票

因此您需要访问输入值,以便将其传递给API。您有两种方法可以做到这一点

解决方案1

在此解决方案中,您需要创建一个本地状态来保存输入值,并在提交时从该状态访问该值。因此您需要定义状态。将changeHandler分配给输入而不是按钮。

注意:如果您需要避免使用第二种解决方案,则此解决方案将在每次更改时导致组件重新呈现。

class SearchBar extends Component {
  constructor(){
     super();
     this.state = { value : "" };
     this.onChangeHandler = this.onChangeHandler.bind(this);
     this.onSubmitHandler = this.onSubmitHandler.bind(this);
  }

  componentDidMount() {
    this.props.fetchWeather();
  }

  onChangeHandler(e){
    this.setState({
      value: e.target.value
    })
  }

  onSubmitHandler(e){
    e.preventDefault();
    let cityName = this.state.value;
    this.props.fetchWeather(cityName);
  }
  render() {
    // console.log(this.props.list.main);

    return (
      <div className="row container">
        <h4 className="blue-text">Weather App</h4>
        <form className="col s12" onSubmit={this.onSubmitHandler}>
          <div className="input-field">
            <input type="text" id="searchbar" onChange={this.onChangeHandler} value={this.state.value} />
            <label htmlFor="searchbar">Search City For Weather Forecast</label>
          </div>
          <div className="input-field ">
            <button className="btn " type="submit">
              Search City
            </button>
          </div>
        </form>
      </div>
    );
  }
}

解决方案2:

您可以通过React refs访问输入值给输入分配一个ref,您可以从提交处理程序访问它。

class SearchBars extends Component {

  componentDidMount() {
    // this.props.fetchWeather();
  }

  onSubmitHandler = (e) => {
    e.preventDefault();
    let cityName = this.searchInput.value;        
    // this.props.fetchWeather(cityName);
  }
  render() {
    // console.log(this.props.list.main);

    return (
      <div className="row container">
        <h4 className="blue-text">Weather App</h4>
        <form className="col s12" onSubmit={this.onSubmitHandler}>
          <div className="input-field">
            <input type="text" id="searchbar" ref={(searchInput) => { this.searchInput = searchInput }} />
            <label htmlFor="searchbar">Search City For Weather Forecast</label>
          </div>
          <div className="input-field ">
            <button className="btn " type="submit">
              Search City
            </button>
          </div>
        </form>
      </div>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.