2017-02-26 130 views
0

林不知道我在做什麼錯在這裏。Axios請求失敗反應

我希望Main組件通過ajax請求方法傳遞給子組件InputForm,它將返回將存儲在Main組件狀態中的結果。

class Main extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
      fetching : false, 
      repos : {} 
     }; 
     this.getGitHubRepo = this.getGitHubRepo.bind(this); 
    } 
    getGitHubRepo(user){ 
     this.setState({ fetching : true }); 
     console.log("form submitted!", user); 
     axios.get(user) 
      .then((response) => { 
       console.log("response =>", response); 
      }) 
      .catch((error) => { 
       console.log("error => ", error); 
      }); 
    } 
    render(){ 
     return(
      <div className = "appContainer"> 
       <InputForm getGitHubRepo = { this.getGitHubRepo } /> 
      </div> 
     ); 
    } 
} 



class InputForm extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      inputValue : "", 
     }; 
     this.recordInput = this.recordInput.bind(this); 
    } 
    recordInput(e){ 
     this.setState({ inputValue : e.target.value }); 
    } 
    render(){ 
     let getPath = `https://api.github.com/${this.state.inputValue}`; 
     return(
      <form onSubmit = {() => this.props.getGitHubRepo(getPath)}> 
       <label htmlFor = "user_input"> 
        Github Username 
       </label> 
       <input id = "user_input" 
         type = "input" 
         onChange = { this.recordInput } /> 
       <input type = "submit" value = "get repos" /> 
      </form> 
     ); 
    } 
} 


ReactDOM.render(<Main />, document.getElementById("app")); 

Here is the jsbin link.

我沒有得到任何結果&我的WebPack服務器刷新頁面。

回答

1

這裏的主要問題是您沒有在表單提交中調用preventDefault。 此外,獲得github回購網站的網址是錯誤的,但這是次要的。

檢查更新jsbin:https://jsbin.com/sujakexamo/1/edit?js,output

class InputForm extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      inputValue : "", 
     }; 
     this.recordInput = this.recordInput.bind(this); 
     this.submit = this.submit.bind(this); 
    } 

    recordInput(e){ 
     this.setState({ inputValue : e.target.value }); 
    } 

    submit (e) { 
     e.preventDefault(); 
     this.props.getGitHubRepo(`https://api.github.com/users/${this.state.inputValue}/repos`); 
    } 

    render(){ 
     return(
      <form onSubmit = {this.submit}> 
       <label htmlFor = "user_input"> 
        Github Username 
       </label> 
       <input id = "user_input" 
         type = "input" 
         onChange = { this.recordInput } /> 
       <input type = "submit" value = "get repos" /> 
      </form> 
     ); 
    } 
} 
+0

謝謝@Canastro。我沒有意識到preventDefault。 – Kayote