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)
    }

 

 

相关文章:

  • 2021-12-22
  • 2021-11-20
  • 2022-12-23
  • 2021-12-11
  • 2021-07-25
  • 2021-11-07
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-02
  • 2021-10-12
  • 2021-08-08
  • 2021-12-20
  • 2021-10-02
相关资源
相似解决方案