- 先订阅,再发布(理解:隔空对话的感觉)
安装第三方库pubsub-jsyarn 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})
}
)
-
适用于任意组件间通信
不像props,限制在父子间传递 -
要在组件的componentWillUnMount中取消订阅
//取消订阅
componentWillUnmount(){
PubSub.unsubscribe(this.token)
}