1.先订阅,再发布(理解:有一种隔空对话的感觉)
2.适用于任意组件间通信
3.要在组件的componentWillUnmount中取消订阅
1、PubSub使用方式
1.1 react导入库
npm install pubsub-js --save
1.2 react 页面引入pubsubjs
import PubSub from 'pubsub-js'
1.3 pubsubjs使用
发送消息:PubSub.publish(名称,参数)
PubSub.publish('atguigu',{isFirst:false,isLoading:true})
订阅消息:var token=PubSub.subscribe(名称,函数)
componentDidMount(){ this.token = PubSub.subscribe('atguigu',(_,stateObj)=>{ //_下划线占位 this.setState(stateObj) }) }
取消订阅:PubSub.unsubscribe(token)
componentWillUnmount(){ PubSub.unsubscribe(this.token) }