1. 首先安装插件
npm install pubsub-js
2. 在使用的页面引入
import PubSub from ‘pubsub-js’
3. 发布消息PubSub.publish
PubSub.publish(‘消息名’, data)
4. 接受消息PubSub.subscribe
PubSub.subscribe(‘消息名’, (a, b) => {})
5. 取消发布订阅 PubSub.unsubscribe
PubSub.unsubscribe(this.token)
演示案例
- Child组件内容
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios'
export default class Child extends Component {
onPublish = () => {
axios.get(`http://192.168.58.110:6666/user/list/id=${15895213568651}`).then(({ data: res }) => {
// 发布消息
PubSub.publish('list', { userList: res.data })
}).catch((err) => {
console.log(err)
})
}
render() {
return (
<div>
<button onClick={this.onPublish}>点我发布消息</button>
</div>
)
}
}
- Child2组件内容
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Child2 extends Component {
render() {
// 初始化状态
state = {
userList: []
}
/**
* 订阅消息,注意点:
* 1. 订阅消息名必须和发布消息名相同
* 2. 订阅消息第二个参数接受一个回调函数,必传两个形参
*/
componentDidMount() {
this.token = PubSub.subscribe('list', (_, data) => {
// const { userList } = this.state
this.setState({...data}) // 相当于 this.setState({userList: data})
})
}
// 页面卸载时取消 消息订阅
componentWillUnmount() {
PubSub.unsubscribe(this.token)
}
return (
const { userList } = this.state
<div>
{ userList.map(item => {
return (
<div className="list">
<div>{item.name}</div>
<div className="list-desc">
<div className="desc">{item.desc}</div>
<div className="time">{item.time}</div>
</div>
</div>
)
}) }
</div>
)
}
}