2017-11-25 9 views
0

api를 호출 한 후에 상태를 업데이트하려고하지만 내 양식이 페이지를 다시로드하지 않도록 preventDefault가 필요합니다. 나는 그것을 시도하는 방식으로 React로 이것을 할 수있는 정보를 찾는 데 어려움을 겪고있다.componentDidMount() 내에서의 preventDefault 방법

<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는 대신, 함수를 직접 부르는 당신에게 아약스 요청을 이동하지 말아야하는 lifeCycle 기능입니다 : "정의되지 않은 재산 '로 preventDefault'을 읽을 수 없습니다 형식 오류"이런 식으로 시도

내가 얻을 별도의 함수를 호출하여 호출하십시오.

<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