参考文档:https://github.com/mroderick/PubSubJS/
pubsub.js消息的发布订阅
- 组件间数据的传递方式【先订阅,再发布】
- props,一层一层传递
- 消息的发布订阅,当嵌套层数比较多,可以用此工具库 ```javascript //先安装 npm install pubsub-js
//引入 import PubSub from ‘pubsub-js’
**订阅消息:**在componentDidMount订阅消怎,注意这里应该在组件一加载时就订阅消息。
```javascript
componentDidMount() {
this.pubsub_token = PubSub.subscribe("saveEditScoreCard".(msg,data))
}
发布消息:使用Pubsub.publish(‘saveEditScoreCard’,data)接收二个参数,第一个是要发送的消息,让订阅,第二个是传输的数据。
Pubsub.publish('saveEditScoreCard',data) //接收二个参数,第一个是要发送的消息,让订阅,第二个是传输的数据。
取消订阅:在componentWillUnmount取消订阅
componentWillUnmount() {
PubSub.unsubscribe(this.pubsub_token );
}
综合demo:list组件订阅消息, button组件发布消息
import React from 'react'
import PubSub from "pubsub-js"
class AddButton extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
add = () => {
//发布消息
PubSub.publish("addObj",{name:'haha', age:15})
}
render() {
return (
<button onClick={this.add}>添加数据</button>
);
}
}
export default AddButton;
import React from 'react';
import PubSub from "pubsub-js"
class List extends React.Component {
constructor(props) {
super(props);
this.state = {
list:[
{name:"iric", age:23},
{name:"lisa", age:25},
{name:"monke", age:17},
{name:"momoko", age:33},
]
};
}
componentDidMount(){
//订阅消息
this.token = PubSub.subscribe("addObj", (msg,data)=> {
console.log(msg,data)
const res = this.state.list;
this.setState({
list:[data,...res]
})
})
}
componentWillUnmount(){
// 取消订阅
PubSub.unsubscribe(token)
}
render() {
const {list} = this.state;
return (
<ul>
{
list.map((item, index) => {
return <li key={index}>{item.name}</li>
})
}
</ul>
);
}
}
export default List;