React与异步请求

fetch

一种以Promise为基础的异步请求。

fetch(url).then(response => {
  return response.json()
}).then( data => {
  // 得到数据
  const { name,html_url } = data.items[0];
  // 更新状态
  this.setState({ repoName:name,repoUrl:html_url }); 
})

Axios

另一种异步请求方式

axios.get(url).then(response => {
  const result = response.data
  const { name,html_url } = result.items[0]
  this.setState({repoName:name,repoUrl:html_url }); 
}).catch((error) => {
  console.log(error.message);
})
  • axios是封装的一个基于XMLHttpRequest对象的ajax,他的风格是Promise风格,可以运行在浏览器和node端。
  • fetch是原生函数,但是老版本的浏览器不支持,为了兼容低版本,还是需要引入兼容库fetch.js。

fetch.js的作用是判断浏览器是否支持fetch,若不支持则转到使用XMLHttpRequest

例子

import React from "react"
import Axios from "Axios"
export default class Qingqiu extends React.Component{
    constructor(props){
        super(props);

        this.state={
            goodsId:"",
            goodsName:""
        }
    }
    render() {
        const { goodsId, goodsName } = this.state;
        if(goodsId == ""){
            return <h2>loading...</h2>
        }else{
            return <h2>The first food is [{ goodsId }]( { goodsName } )</h2>
        }
    }
    componentDidMount() {
        const url = `http://jspang.com/DemoApi/oftenGoods.php`;
        let _this=this;
        Axios.get(url).then( response => {
            const data = response.data;
            console.log(data);
            _this.setState(data[0]);
        } ).catch(( error ) => {
            console.log(error);
        }); 
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容