2017-09-13 118 views
0

我正在使用axios發出ajax請求。我是一個新手提出ajax請求,並不理解爲什麼這段代碼不工作?我刪除了一些與這個問題無關的代碼,爲什麼它不工作。錯誤顯示爲「GET https://api.github.com/users/ $%7Bthis.state.usersName%7D 404(Not Found)」。也許我在寫請求錯誤的URL部分...使用axios反應ajax請求

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import App from './App'; 
import registerServiceWorker from './registerServiceWorker'; 
import axios from 'axios'; 

const Card = (props) => { 
    return(
     <div style={{margin: '1em'}}> 
      <img src={props.Avatar_URL} width="120px"/> 
      <div> 
       <div>{props.Name}</div> 
       <div>{props.Company}</div> 
      </div> 
     </div> 
    ); 

}; 

const CardList= (props) => { 
    return(
     <div> 
      {props.Card.map(card => <Card {...card}/>)} 
     </div> 

    ); 
}; 

class MyForm extends React.Component{ 
    state = { userName: '' } 
    handlesSubmit = (event) => { 
     event.preventDefault(); 
     console.log('Event: Form Submitted:', this.state.userName); 
     axios.get("api.github.com/users/" + this.state.userName).then(response => { 
      console.log(response); 
     }) 

    }; 
    render(){ 
     return(
      <form onSubmit={this.handlesSubmit}> 
       <div style={{margin: '1em'}}> 
        <input type="text" placeholder="@Github" 
           value={this.state.userName} 
           onChange={(event) => this.setState({ userName: event.target.value})}/> 
        <button type="submit">Search</button> 
       </div> 
      </form> 
     ); 
    }; 
}; 

class MyApp extends React.Component{ 
    render(){ 
     return(
      <div> 
       <MyForm /> 
       <CardList Card={data} /> 
      </div> 
     ); 
    }; 
}; 

let data = [ 
    { 
     Avatar_URL: "https://avatars2.githubusercontent.com/u/35?v=4", 
     Name: "Kevin Williams", 
     Company: "Oracle" 
    }, 
    { 
     Avatar_URL: "https://avatars2.githubusercontent.com/u/36?v=4", 
     Name: "Dave Fayram", 
     Company: "Udacity, Inc" 
    } 
] 

ReactDOM.render(
    <MyApp />, 
    document.getElementById('root') 
); 
+0

404是一個「找不到網頁錯誤」,因此檢查網址 – AlexVestin

+0

都能跟得上它沒有任何工作..我什至嘗試把它放入一個變量,並沒有工作 –

+0

你正在使用usersName而獲取配置文件,但用戶名在 – AlexVestin

回答

0

好吧好吧然後,

第一data

<CardList Card={data} /> 

沒有初始化,而忽視了卡組件片刻。

axios.get('http://api.github.com/users/${this.state.usersName}') 

應該

axios.get('http://api.github.com/users/' + this.state.userName) 

而且我猜你要使用的數據的卡,你要麼將不得不在屋裏MyForm的渲染,或設置MyApp的一個狀態回調進入MyForm

如上所述卡未導入或定義。

github api返回值的字典,該地圖不能(直接)工作。

我覺得你應該去通過教程有點更緊密

+1

你可以看到這不是一個真正的URL嗎?你需要指定請求的完整路徑,即。在https://api.github.com/users/ – AlexVestin

1

您嘗試使用模板文字,但您使用了錯誤的qoute template literal

,或者你可以將字符串:

模板文字:`http://api.github.com/users/ $ {} this.state.userName

或 contatenate串'http://api.github.com/users/' + this.state.userName'

而且我看不出你導入或聲明組件,是一個觀察

+0

中添加https://我沒有添加「http://」我很傻。 –