使用axios反应ajax请求

问题描述 投票:0回答:1

我正在使用axios来发出ajax请求。我是制作ajax请求的新手,而不理解为什么这段代码不起作用?我删除了一些与此问题无关的代码,说明为什么它不起作用。显示的错误是“GET https://api.github.com/users/ $%7Bthis.state.usersName%7D 404(Not Found)”。也许我在网址部分写错了请求...

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')  
);
ajax reactjs axios
1个回答
1
投票

您正在尝试使用模板文字,但您使用的是错误的引用qazxsw poi

或者你可以连接字符串:

template literal:`template literal $ {this.state.userName}

或者连接字符串http://api.github.com/users/

我没有看到你导入或声明卡组件的位置,是观察

© www.soinside.com 2019 - 2024. All rights reserved.