利用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也是一种好的选择!

posted @ 2020-09-13 19:09  jacksonni  阅读(534)  评论(0编辑  收藏  举报