• 03-React网络通信(Axios, PubSubJs, Fetch)


    创建项目

    create-react-app react_axios
    

    添加axios依赖

    yarn add axios
    

    配置代理

    在package.json中配置

    "proxy": "http://localhost:8080"
    

    使用时需要将访问端口改为自身端口

    1. import React, {Component} from 'react';
    2. import axios from "axios";
    3. class App extends Component {
    4. queryData = () => {
    5. # 访问3000端口, 然后通过代理,访问8080
    6. axios.get("http://localhost:3000/students").then(
    7. response=> {
    8. console.log(response)
    9. },
    10. error => {
    11. console.log(error)
    12. }
    13. )
    14. }
    15. render() {
    16. return (
    17. <div>
    18. <button onClick={this.queryData}>获取数据</button>
    19. </div>
    20. );
    21. }
    22. }
    23. export default App;

    但是这样会存在一个问题, 那就是访问自身3000存在的资源就不会转发给8080

    修改为

    其实就是public/index.html

    多代理配置

    在src下新建setupProxy.js, 记得删除package.json中的proxy

    1. // 需要写 CJS语法
    2. // 导入代理中间件
    3. const {createProxyMiddleware} = require('http-proxy-middleware')
    4. module.exports = function (app) {
    5. app.use(
    6. createProxyMiddleware('/test', {
    7. target: 'http://localhost:8080',
    8. changeOrigin: true,
    9. pathRewrite:{
    10. '^/test':''
    11. }
    12. }),
    13. createProxyMiddleware('/dev', {
    14. target: 'http://localhost:8081',
    15. changeOrigin: true,
    16. pathRewrite:{
    17. '^/dev':''
    18. }
    19. })
    20. )
    21. }

    使用时添加前缀

    这样就可以转发多个网络请求了, 通过前缀区分,要代理到哪里

    连续解构赋值

    1. const key = {
    2. value:{
    3. title:'123'
    4. }
    5. }
    6. # 连续解构赋值
    7. const {value:{title}} = key
    8. # 只能使用title, 而不能使用value

    解构赋值后重命名

    1. const key = {
    2. value:{
    3. title:'123'
    4. }
    5. }
    6. # 连续解构赋值 将title重命名为标题
    7. const {value:{title:bt}} = key

    消息订阅与发布(PubSubJs)

    添加依赖

    yarn add pubsub-js
    

    使用

    App.js

    1. import React, {Component} from 'react';
    2. import axios from "axios";
    3. import Pub from "./components/pub/pub";
    4. import Sub from "./components/sub/sub";
    5. class App extends Component {
    6. render() {
    7. return (
    8. <div>
    9. <Pub/>
    10. <Sub/>
    11. div>
    12. );
    13. }
    14. }
    15. export default App;

    Pub.js

    1. import React, {Component} from 'react';
    2. import PubSub from "pubsub-js";
    3. class Pub extends Component {
    4. render() {
    5. return (
    6. <div>
    7. <button onClick={this.send}>发送消息</button>
    8. </div>
    9. );
    10. }
    11. send = () => {
    12. const items = ['a','b','c']
    13. PubSub.publish('pub',items)
    14. console.log("发送数据")
    15. }
    16. }
    17. export default Pub;

    Sub.js

    1. import React, {Component} from 'react';
    2. import PubSub from 'pubsub-js'
    3. class Sub extends Component {
    4. state = {
    5. items: ['html', 'js', 'css']
    6. }
    7. componentDidMount = () => {
    8. // 订阅消息
    9. console.log("订阅消息")
    10. this.token = PubSub.subscribe('pub', (_, items) => {
    11. console.log("sub接收到数据", items);
    12. this.setState({items})
    13. })
    14. }
    15. componentWillUnmount() {
    16. // 在组件卸载时取消订阅
    17. PubSub.unsubscribe(this.token)
    18. }
    19. render() {
    20. const {items} = this.state
    21. return (
    22. <div>
    23. <ul>
    24. {
    25. items.map(item => {
    26. return <li key={item}>{item}</li>
    27. })
    28. }
    29. </ul>
    30. </div>
    31. );
    32. }
    33. }
    34. export default Sub;

    执行结果

    效果没有问题, 但是消息被订阅了两次

    componentDidMount函数被连续执行两次的问题

    因为我在订阅之后发现这个生命周期被连续执行两次,导致一下订阅了两次,出现问题

    解决办法

    把index.js中的React.StrictMode删除即可

    删除后发现剩余此一次一次了

    扩展知识: Fetch

    文档

    https://github.github.io/fetch/
    

    特点

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

    Get请求

    1. fetch('http://localhost:3000/test/students').then(
    2. response => {
    3. console.log("联系服务器成功",response)
    4. return response.json()
    5. }
    6. ).then(
    7. response => {
    8. console.log("获取数据成功",response)
    9. }
    10. ).catch(
    11. error => {
    12. console.log("失败",error)
    13. }
    14. )

    Post请求

    1. const items = ['a','b','c']
    2. fetch('http://localhost:3000/test/students',{
    3. method:'POST',
    4. body:JSON.stringify(items)
    5. }).then(
    6. response => {
    7. console.log("联系服务器成功",response)
    8. return response.json()
    9. }
    10. ).then(
    11. response => {
    12. console.log("获取数据成功",response)
    13. }
    14. ).catch(
    15. error => {
    16. console.log("失败",error)
    17. }
    18. )

    优化写法

    1. try {
    2. const response = await fetch('http://localhost:3000/test/students', {
    3. method: 'POST',
    4. body: JSON.stringify(items)
    5. })
    6. const data = await response.json()
    7. console.log(data)
    8. } catch (e) {
    9. console.log("失败了",e)
    10. }

    记得在外部函数写async

  • 相关阅读:
    [C++]set判断两个元素相等
    k8s client-go源码分析 informer源码分析(5)-Controller&Processor源码分析
    redis批量先查缓存再查数据库
    STM8S系列基于STVD开发,标准外设库函数开发环境搭建
    谁的孙子最多II
    Java中的泛型:高效编程的利器
    零时科技 || BXH攻击事件分析
    基于MATLAB的室内可见光调制解调通信系统
    2.在命令行下使用 Linux 帮助信息
    SWT/Jface(1): 表格的创建和渲染
  • 原文地址:https://blog.csdn.net/flowerStream/article/details/126493659