安装pubsub-js
npm install pubsub-js --save
发布消息
import React, {Component} from 'react';
import PubSub from "pubsub-js";
class Count extends Component{
increment=()=> {
PubSub.publish('updateCount','发布消息')
}
render() {
return (
<div>
<button onClick={this.increment}>发布消息</button>
</div>
);
}
}
export default Count;
订阅消息
import React, {Component} from 'react';
import PubSub from "pubsub-js";
class Person extends Component{
state={
info:'默认值'
}
componentDidMount() {
this.pubId=PubSub.subscribe('updateCount',(_,stateObj)=>{
this.setState({info:stateObj})
})
}
componentWillUnmount(){
PubSub.unsubscribe(this.pubId)
}
render() {
const {info}=this.state
return (
<div>
<h2>接收消息:{info}</h2>
</div>
);
}
}
export default Person;
|