四、React Ajax

郁子大约 3 分钟约 926 字笔记React16.8尚硅谷张天禹Ajax

(一)理解

1.前置说明

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

2.常用的 ajax 请求库

  • JQuery
    • 比较重,需要另外引入,不建议使用
  • Axios
    • 轻量级,建议使用
    • 封装 XmlHttpRequest 对象的 ajax
    • Promise 风格
    • 可以用在浏览器端和 Node 服务器端

(二)Axios

1.文档

2.相关 API

1)GET 请求

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

axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

2)POST 请求

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

(三)react 脚手架配置代理总结

1.方法一

  • package.json 中追加如下配置
"proxy": "http://localhost:5000"
  • 优点:配置简单,前端请求资源时可以不加任何前缀
  • 缺点:不能配置多个代理
  • 工作方式:上述方式配置代理,当请求了 3000 不存在的资源时,那么该请求会转发给 5000 (优先匹配前端资源)

2.方法二

  • 创建代理配置文件:
    • 在 src 下创建配置文件:src/setupProxy.js
  • 编写 setupProxy.js 配置具体代理规则:
const proxy = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    proxy("/api1", {
      //api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
      target: "http://localhost:5000", //配置转发目标地址(能返回数据的服务器地址)
      changeOrigin: true, //控制服务器接收到的请求头中host字段的值
      /*
          changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
          changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:3000
          changeOrigin默认值为false,但我们一般将changeOrigin值设为true
        */
      pathRewrite: { "^/api1": "" }, //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
    }),
    proxy("/api2", {
      target: "http://localhost:5001",
      changeOrigin: true,
      pathRewrite: { "^/api2": "" },
    }),
  );
};
  • 优点:可以配置多个代理,可以灵活的控制请求是否走代理
  • 缺点:配置繁琐,前端请求资源时必须加前缀

(四)消息订阅-发布机制

1.工具库

  • PubSubJS

2.下载

npm i pubsub-js --save

3.使用

// 引入
import PubSub from "pubsub-js";

// 订阅消息
this.token = PubSub.subscribe("delete", function (data) {});

// 发布消息
PubSub.publish("delete", data);

// 取消订阅
PubSub.unsubscribe(this.token);

(五)扩展:Fetch

1.文档

2.特点

  • fetch:原生函数,不再使用 XmlHttpRequest 对象提交 ajax 请求
  • 老版本浏览器可能不支持

3.相关 API

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.stringfy(data),
})
  .then(function (data) {
    console.log(data);
  })
  .catch(function (e) {
    console.log(e);
  });

(六)GitHub 用户搜索案例

  • 案例请求地址:https://api.github.com/search/users?q=xxxxxx

1.设计状态时要考虑全面

  • 例如:带有网络请求的组件,要考虑请求失败如何处理

2.ES6 小知识点:解构赋值 + 重命名

let obj = {
  a: {
    b: 1,
  },
};

// 传统解构赋值
const { a } = obj;

// 连续解构赋值
const {
  a: { b },
} = obj;

// 连续解构赋值+重命名属性
const {
  a: { b: value },
} = obj;

3.消息订阅与发布机制

  • 先订阅,后发布
    • 理解:有一种隔空对话的感觉
  • 适用于任意组件间通信
  • 要在组件的 componentWillUnmount() 钩子中取消订阅

4.fetch 发送请求

  • “关注分离”的设计思想
try {
  const response = await fetch(`/api/search/users2?q=${keyWord}`);
  const res = await response.json();
  console.log(res);
} catch (err) {
  console.log("请求出错", err);
}
上次编辑于: