我使用axios发出ajax请求。我是制作ajax请求的新手而不理解为什么这段代码不起作用?我删除了一些与此问题无关的代码,说明为什么它不起作用。显示的错误是" GET https://api.github.com/users/ $%7Bthis.state.usersName%7D 404(未找到)"。也许我在网址部分写错了请求...
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 :(得分:1)
您正在尝试使用模板文字,但使用了错误的qoute template literal
或者你可以连接字符串:
模板文字:`http://api.github.com/users/ $ {this.state.userName}
或
contatenate string 'http://api.github.com/users/' + this.state.userName'
我看不到你导入或声明卡组件的位置,是观察