zoukankan      html  css  js  c++  java
  • 利用PubSub进行react组件间通信

    本篇LIST

    问题引入
    什么是PubSub
    小结
    

    1.问题引入

    当我们在组件化开发中,避免不了不同组件的之间的通信。我们一般利用props属性来进行层级嵌套中的数据传递,还可以利用redux这一个库来集中管理react的状态数据。哪还有没有别的方法呢?

    2.什么是PubSub

    这是一个第三方的包,我们可以利用他来进行组件间的通信。

    3.那我们如何使用呢?

    1.先在js中引入

    这里有两种方法,引入:

    import PubSub from 'pubsub-js'
    
    // or when using CommonJS
    const PubSub = require('pubsub-js');
    

    2.基础的使用方法

    发布与订阅:

    // create a function to subscribe to topics
    var mySubscriber = function (msg, data) {
        console.log( msg, data );
    };
    
    // add the function to the list of subscribers for a particular topic
    // we're keeping the returned token, in order to be able to unsubscribe
    // from the topic later on
    var token = PubSub.subscribe('MY TOPIC', mySubscriber);
    
    // publish a topic asynchronously
    PubSub.publish('MY TOPIC', 'hello world!');
    
    // publish a topic synchronously, which is faster in some environments,
    // but will get confusing when one topic triggers new topics in the
    // same execution chain
    // USE WITH CAUTION, HERE BE DRAGONS!!!
    PubSub.publishSync('MY TOPIC', 'hello world!');
    

    3.取消订阅

    // create a function to receive the topic
    var mySubscriber = function(msg, data) {
        console.log(msg, data);
    };
    
    // unsubscribe mySubscriber from ALL topics
    PubSub.unsubscribe(mySubscriber);
    

    4.取消所有的订阅

    PubSub.clearAllSubscriptions(); // all subscriptions are removed

    3.小结

    利用发布订阅来进行组件的通信,我们不难看出是十分简单并且高效的。在redux的考虑之外pubsub也是一种好的选择!


        感谢您花时间阅读此篇文章,如果您觉得看了这篇文章之后心情还比较高兴,可以打赏一下,请博主喝上一杯咖啡,让博主继续码字……
        本文版权归作者和博客园共有,来源网址:https://blog.csdn.net/weixin_46498102 欢迎各位转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接
  • 相关阅读:
    postman 调用webservice方法
    .net core 传JSON对象Controller接收不到的问题处理方法
    java不同基本类型之间的运算
    重写和重载
    java基本数据类型介绍
    浏览器tab页签切换事件
    设计模式之观察者模式
    设计模式之状态模式
    设计模式之备忘录模式
    设计模式之迭代器模式
  • 原文地址:https://www.cnblogs.com/jackson1/p/13662613.html
Copyright © 2011-2022 走看看