React消息订阅与发布机制

  1. 先订阅,再发布(理解:隔空对话的感觉)
    安装第三方库pubsub-js yarn add pubsub-js,利用钩子函数componentDidMount在组件挂载后subscribe()函数进行订阅消息,该行为会返回一个token值,供**unsubscribe()**取消订阅时使用,根据token取消对应的消息
	//订阅
    componentDidMount(){
        this.token = PubSub.subscribe('usersData',(_,data) => {
            console.log('订阅消息:',data)
            this.setState({...data})
        })
    }

publish()进行发布消息
	//发布消息
	PubSub.publish('usersData',{isFirst:false,isLoading:true})
    //发送网络请求
    axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
        response => {
            // this.props.UpdateAppState({isLoading:false,users:response.data.items})
            PubSub.publish('usersData',{isLoading:false,users:response.data.items})

        },
        error => {
            //this.props.UpdateAppState({isLoading:false,err:error.message})}
            PubSub.publish('usersData',{isLoading:false,err:error.message})
        }
            
    )
  1. 适用于任意组件间通信
    不像props,限制在父子间传递

  2. 要在组件的componentWillUnMount中取消订阅

    //取消订阅
    componentWillUnmount(){
        PubSub.unsubscribe(this.token)
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值