参考文档:https://github.com/mroderick/PubSubJS/
    pubsub.js消息的发布订阅

    • 组件间数据的传递方式【先订阅,再发布】
      • props,一层一层传递
      • 消息的发布订阅,当嵌套层数比较多,可以用此工具库 ```javascript //先安装 npm install pubsub-js

    //引入 import PubSub from ‘pubsub-js’

    1. **订阅消息:**在componentDidMount订阅消怎,注意这里应该在组件一加载时就订阅消息。
    2. ```javascript
    3. componentDidMount() {
    4. this.pubsub_token = PubSub.subscribe("saveEditScoreCard".(msg,data))
    5. }

    发布消息:使用Pubsub.publish(‘saveEditScoreCard’,data)接收二个参数,第一个是要发送的消息,让订阅,第二个是传输的数据。

    1. Pubsub.publish('saveEditScoreCard',data) //接收二个参数,第一个是要发送的消息,让订阅,第二个是传输的数据。

    取消订阅:在componentWillUnmount取消订阅

    1. componentWillUnmount() {
    2. PubSub.unsubscribe(this.pubsub_token );
    3. }

    综合demo:list组件订阅消息, button组件发布消息

    1. import React from 'react'
    2. import PubSub from "pubsub-js"
    3. class AddButton extends React.Component {
    4. constructor(props) {
    5. super(props);
    6. this.state = { };
    7. }
    8. add = () => {
    9. //发布消息
    10. PubSub.publish("addObj",{name:'haha', age:15})
    11. }
    12. render() {
    13. return (
    14. <button onClick={this.add}>添加数据</button>
    15. );
    16. }
    17. }
    18. export default AddButton;
    1. import React from 'react';
    2. import PubSub from "pubsub-js"
    3. class List extends React.Component {
    4. constructor(props) {
    5. super(props);
    6. this.state = {
    7. list:[
    8. {name:"iric", age:23},
    9. {name:"lisa", age:25},
    10. {name:"monke", age:17},
    11. {name:"momoko", age:33},
    12. ]
    13. };
    14. }
    15. componentDidMount(){
    16. //订阅消息
    17. this.token = PubSub.subscribe("addObj", (msg,data)=> {
    18. console.log(msg,data)
    19. const res = this.state.list;
    20. this.setState({
    21. list:[data,...res]
    22. })
    23. })
    24. }
    25. componentWillUnmount(){
    26. // 取消订阅
    27. PubSub.unsubscribe(token)
    28. }
    29. render() {
    30. const {list} = this.state;
    31. return (
    32. <ul>
    33. {
    34. list.map((item, index) => {
    35. return <li key={index}>{item.name}</li>
    36. })
    37. }
    38. </ul>
    39. );
    40. }
    41. }
    42. export default List;