react 第四章—— ajax

2019-07-26  本文已影响0人  定格r

1.理解:

  1. React本身只关注于界面, 并不包含发送ajax请求的代码
  2. 前端应用需要通过ajax请求与后台进行交互(json数据)
  3. react应用中需要集成第三方ajax库(或自己封装)

2.常用的ajax请求库

  1. jQuery: 比较重, 如果需要另外引入不建议使用
  2. axios: 轻量级, 建议使用
    a. 封装 ax
    b. promise风格
    c. 可以用在浏览器端和node服务器端
  3. fetch: 原生函数, 但老版本浏览器不支持
    a. 不再使用XmlHttpRequest对象提交ajax请求
    b. 为了兼容低版本的浏览器, 可以引入兼容库fetch.js

3.相关 API

- axios

1> GET 请求

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);
  });

2> POST请求

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

- Fetch

1> GET 请求

fetch(url).then(function(response) {
  return response.json()
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
});

2> POST请求

fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
}).then(function(data) {
  console.log(data)
}).catch(function(e) {
  console.log(e)
})

重点:
componentWillReceiveProps(nextProps): 监视接收到新的props, 发送ajax使用axios库发送ajax请求

上一篇 下一篇

猜你喜欢

热点阅读