2017-11-25 7 views
0

私はAPIを呼び出した後に状態を更新しようとしていますが、私のフォームがページの再読み込みをトリガーしないように防ぐ必要があります。 Reactでこれをやり遂げることができるような情報を見つけるのは難しいです。どのようにpreventDefault componentDidMount()

<form className="form-inline" onSubmit={this.componentDidMount} > 
     <input 
      placeholder="Search your city!" 
      className="form-control" 
      value={this.state.term} 
      onChange={this.onInputChange}></input> 
     <button 
      type="submit" 
      className="btn btn-default">Search</button> 
</form> 

componentDidMount(event) { 
    event.preventDefault(); 
    const API_KEY = 'ju2nvu4nvun42vgrw'; 
    const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast? 
         appid=${API_KEY}`; 
    const city = this.state.term; 
    const url = `${ROOT_URL}&q=${city}`; 
    axios.get(url) 
     .then(function (response) { 
      this.setState({ 
       days: response.data 
      }) 
    }); 
} 

答えて

1

componentDidMountがあなたの代わりに、直接関数を呼び出すにはあなたのAJAX要求を移動してはならない、lifeCycle機能である:「未定義のプロパティ 『でpreventDefault』を読み取ることができませんTypeError例外」このようにそれをしようと

私が取得します別の関数を呼び出すと

<form className="form-inline" onSubmit={this.handleSubmit} > 
     <input 
      placeholder="Search your city!" 
      className="form-control" 
      value={this.state.term} 
      onChange={this.onInputChange}></input> 
     <button 
      type="submit" 
      className="btn btn-default">Search</button> 
</form> 

handleSubmit(event) { 
    event.preventDefault(); 
    const API_KEY = 'ju2nvu4nvun42vgrw'; 
    const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast? 
         appid=${API_KEY}`; 
    const city = this.state.term; 
    const url = `${ROOT_URL}&q=${city}`; 
    axios.get(url) 
     .then(function (response) { 
      this.setState({ 
       days: response.data 
      }) 
    }); 
} 
+0

ありがとう – Andrew

関連する問題