react中使用pubsub-js库进行发布订阅模式的练习

1,584 阅读2分钟
1,什么是发布订阅模式

个人理解,发布订阅就像是现在大家刷某音一样,关注了某个博主之后,会给推送他后面新发布的内容。博主就是(publish)发布者,关注者就是(subscribe)订阅者。

2,react中发布订阅

一般来说,当我们对组件进行拆分了之后,组件的状态管理是需要思考的问题。类似于这样的

image.png 可以将其拆分为三部分,比如header,left,right。 可以有两个思路进行。一种是将外面包上一层壳。将所有状态存入最外层的容器里面;另外一种是通过发布订阅的模式进行兄弟组件之间的传值(发布订阅模式需要这两个组件在页面都渲染了(这样才能保证功能正常),另外的是当组件卸载的时候要取消订阅,不然的话就会造成对已经卸载的组件进行操作,会造成内存泄漏的。)

3,代码

兄弟组件的发布订阅

import React, { Component } from 'react'
// 发布订阅模式
import PubSub from 'pubsub-js'

export const Login = (props) => {
    // 函数组件
    const dataObj = {sex:{nan: '男'} , age: [12,13,14], height: 178};
    const {sex:{nan}, age, height} = dataObj
    console.log(nan,...age ,height)
   
    const callWillLogin = ()=>{
     console.log('我是login里面的数据')
      // 发布消息
      PubSub.publish('call_article', dataObj)
    }
    return (
        <div style={{
            width: '100px',
            height: '100px',
            background: 'green'
        }}>
            <button onClick = {()=>callWillLogin()}>点击登录了</button>
        </div>
    )
}

另一个组件的

import React, { Component } from 'react'
// 发布订阅模式
import PubSub from 'pubsub-js'

export class index extends Component {
    state = {
        stateObj: {},
    }

  componentDidMount(){
    //  订阅,将订阅的事件取一个名字,当组件卸载的时候进行清除
        this.Token = PubSub.subscribe('call_article',(msg,data)=>{
        console.log('我是article里面得到的数据',msg,data)
        this.setState({stateObj:data})
        console.log(this.state,'stateObj')
     })
  }

  componentWillUnmount(){
    // 取消订阅
      console.log('卸载',this.Token)
      PubSub.unsubscribe(this.Token);
  }
  render() {
      const {sex, age, height} = this.state.stateObj
    return (
      <div>
       <div>{height}</div>
      </div>
    )
  }
}

export default index

初学react,有不对的地方望各位大佬能够指点迷津。