我是靠谱客的博主 无私小天鹅,最近开发中收集的这篇文章主要介绍react数据交互,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

数据交互

React没有集成ajax功能,要使用ajax功能,可以使用官方推荐的axios.js库来做ajax的交互。 axios库的下载地址:https://github.com/axios/axios/releases

axios使用方法

常用参数:
1、url 请求地址
2、method 请求方式,默认是'GET',常用的还有'POST'
3、responsetype 设置返回的数据格式,常用的是'json'格式,也可以设置为'text'或者'html'
4、params 设置发送给服务器的数据
5、then 设置请求成功后的回调函数
6、catch 设置请求失败后的回调函数

axios完整写法:

axios({
  url: '/user/12345',
  method: 'get',
  responsetype:'json',
  params: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

axios请求的写法也写成get方式后post方式。

执行get请求

// 为给定 ID 的 user 创建请求
// then是请求成功时的响应,catch是请求失败时的响应

axios.get('/user?ID=12345')
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});


// 可选地,上面的请求可以这样做
axios.get('/user', {
  params: {
    ID: 12345
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

执行post请求

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

最后

以上就是无私小天鹅为你收集整理的react数据交互的全部内容,希望文章能够帮你解决react数据交互所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部