React学习笔记(三):请求数据服务

React学习笔记(三):请求数据服务

react中没有提供专门的请求数据的模块,但我们可以使用任何第三方请求数据模块实现请求数据,也可以自己写,下面举两个例子。

axios(需要后端允许跨域)

1、安装,cnpm install axios --save
2、导入,import axios from ‘axios’
3、使用,api是你向后端请求服务的地址,res就是你接收到后端给你的数据,catch是对出错处理,可以不写。

axios.get(api)
     .then( (res) => {
         //在这里获取到数据可以保存在state中使用
        this.setState({
            list:res.data
        })
    })
     .catch((err) => {
        console.log(err);
     });

fetch-jsonp

1、安装,cnpm install fetch-jsonp --save
2、导入,import fetchJsonp from ‘fetch-jsonp’
3、使用

fetchJsonp(api)
.then((res) => {
    return res.json()
})
.then((json) => {
    //在这里获取到数据可以保存在state中使用
    this.setState({
        list:json.result
    })
})
.catch((err) => {
    console.log(err)
})

猜你喜欢

转载自blog.csdn.net/weixin_43943881/article/details/87100904