【问题标题】:How to clear input text box, after obtaining the result from API in React从React中的API获取结果后如何清除输入文本框
【发布时间】:2019-09-01 13:21:18
【问题描述】:

我需要有关我的 React 天气应用程序的帮助。我正在寻找一个城市以从 API 获取天气预报。一切正常。当我输入城市名称并搜索时,会出现结果。但是我想在获得结果时清除输入文本。我做了以下resetForm,它正在清除输入字段,但同时清除API的结果。

class Form extends React.Component{

    render(){
        resetForm = () => {
        this.refs.inputId.value="";
      }
        return(
            <form onSubmit={this.props.getWeather}>
                <input type="text" name="city" placeholder="Type a city name..." ref="inputID" />
                <button>Search</button>
            </form>
        );
    }


};

getWeather = async (e) =>{
    this.setState({loading: true});
    e.preventDefault();
    const city = e.target.elements.city.value;
    const api_call = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
    const data = await api_call.json();

    if(city){
      console.log(data);
      this.setState({
        temperature: data.main.temp,
        city: data.name,
        humidity: data.main.humidity,
        description: data.weather[0].description,
        error: "",
        loading:false,

      });
    }else{
      this.setState({ 
        temperature: undefined,
        city: undefined,
        humidity: undefined,
        description: undefined,
        error: "Please enter the city and the country name!",
        loading:false,

      });
    }

【问题讨论】:

    标签: reactjs api


    【解决方案1】:

    Controlled Components 是最简单的方法。

    在父组件中,你需要维护一个state变量并更改处理函数并将其传递给Form组件,

    state = {
        inputCity: ''   //You can add this in your existing state
    } 
    

    还有变化处理函数,

    onCityChange = (e) => {
        this.setState({inputCity : e.target.value})
    }
    

    现在您可以将它们传递给您的 Form 组件,

    <Form inputCity={this.state.inputCity} onCityChange={this.onCityChange} getWeather={this.getWeather}/>
    

    你Form组件应该是,

    class Form extends React.Component{
    
        render(){
            return(
                <form onSubmit={this.props.getWeather}>
                    <input type="text" name="city" placeholder="Type a city name..." value={this.props.inputCity} onChange={this.props.onCityChange}/>
                    <button>Search</button>
                </form>
            );
        }
    };
    

    你的getWeather函数应该是,

    getWeather = async (e) =>{
        this.setState({loading: true});
        e.preventDefault();
        const city = this.state.inputCity;   //take the city from state directly
        const api_call = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
        const data = await api_call.json();
    
        if(data){   //instead of city it should be data here
          console.log(data);
          this.setState({
            temperature: data.main.temp,
            city: data.name,
            humidity: data.main.humidity,
            description: data.weather[0].description,
            error: "",
            loading:false,
            inputCity: ""   //here you can clear the city 
          });
        }else{
          this.setState({ 
            temperature: undefined,
            city: undefined,
            humidity: undefined,
            description: undefined,
            error: "Please enter the city and the country name!",
            loading:false,
    
          });
        }
    

    【讨论】:

      【解决方案2】:

      试试这个:我已经修改了你的代码以使用状态, ref 很好,但通常被认为不是最有效的方法:

      this.setState 也有一个回调,因为它是一个异步操作,你可以在加载设置为 true 之后,在响应成功或失败之后(只要来自服务器的响应是已收到),将加载状态设置为 false 并清除输入。

      您的代码的其余部分都很好,除了一些调整之外,它现在可以工作了。 在此处阅读有关受控输入的更多信息:https://reactjs.org/docs/forms.html

      import React from "react";
      import ReactDOM from "react-dom";
      
      import "./styles.css";
      
      class Form extends React.Component{
        state = {
          loading:false,
          temperature: '',
          city: '',
          humidity: '',
          description: '',
          error: '',
          cityName: ''
        }
      
        handleChange = (e) => {
          this.setState({ city: e.target.value });
        }
      
        getWeather =  (e) => {
          e.preventDefault();
          this.setState({loading: true}, async () => {
            const {city} = this.state;
            const api_call = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
            const data = await api_call.json();
      
            if(data){
              console.log(data);
              this.setState({
                temperature: data.main.temp,
                cityName: data.name,
                humidity: data.main.humidity,
                description: data.weather[0].description,
                error: "",
                loading:false,
      
              }, () => {
                this.setState({ city: '' })
              });
            }else{
              this.setState({ 
                temperature: undefined,
                cityName: undefined,
                humidity: undefined,
                description: undefined,
                error: "Please enter the city and the country name!",
                loading:false,
      
              }, () => {
                this.setState({ city: '' })
              });
            }
          });
      }
        render(){
            return(
                <form onSubmit={this.getWeather}>
                    <input type="text" 
                      name="city" 
                      value={this.state.city}
                      placeholder="Type a city name..." 
                      onChange={this.handleChange} />
                    <button>Search</button>
                </form>
            );
        }
      
      
      };
      
      const rootElement = document.getElementById("root");
      ReactDOM.render(<Form />, rootElement);
      

      沙盒链接:https://codesandbox.io/s/zen-browser-e2rh8?fontsize=14

      【讨论】:

        猜你喜欢
        • 2018-04-06
        • 1970-01-01
        • 2021-11-23
        • 2017-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-21
        • 2012-12-09
        相关资源
        最近更新 更多