React(脚手架)——create-react-app撸api

2019-03-08  本文已影响0人  感觉不错哦
简单讲下axios的使用

https://www.npmjs.com/package/axios

npm install axios --save

axios跟vue一样,按需引入,不建议全局使用,安装好之后在需要引入的组件引入

import axios from 'axios'

https://api.apiopen.top/EmailSearch?number=1012002](https://api.apiopen.top/EmailSearch?number=1012002
百度开放的接口还是很多的,随便找了一个

    import React,{Component} from 'react'
    import axios from 'axios'

    class New extends Component {
        constructor(props) {
            super(props);
            this.state = {
                data:[]
            };    
        }

        get(){
            axios.get('https://api.apiopen.top/EmailSearch?number=1012002')
                .then((response)=> {
                    this.setState({
                        data:response.data.result.data
                    })
                    console.log(response);
                })
                .catch((error) =>{  
                    console.log(error);
                });
        }
        render() {
            return (
                <div>
                    <h2>axios 获取数据</h2>
                    <button onClick={this.get.bind(this)}>getData</button>
                    {
                        this.state.data.map((v,i)=>{
                            return <h5 key={i}>{v.context}</h5>
                        })
                    }
                </div>
            );
        }
        
    }


    export default New;

axios的写法其实没有什么需要记忆的,完全可以复制粘贴,那么在react中需要注意的是箭头函数!使用箭头函数不用担心this指向问题,所以注意就是复制的时候把es5改成es6,当然 如果你有一个好组长的话就很舒服,axios肯定是要封装的

不过axios好像不支持jsonp,不过也无所谓了都9012了还有跨域这种东西真的是,作为一个前端只想骂脏话,如果实在没法就使用fetch-jsonp吧,毕竟我们斗不过他们的

上一篇 下一篇

猜你喜欢

热点阅读