Message subscription and publishing pubsub

Message subscription and publishing pubsub

Component communication in react can be achieved through message subscription and publishing.
The principle is similar to:

订阅报纸:
1、送报地址、订阅什么报纸
2、邮递员送报纸
订阅消息:
1、消息名
2、发布消息

1, Tool store:
PubSubJS
2, Download:

npm install pubsub-js --save

3.Use:

import PubSub from 'pubsub-js'//引入

PubSUb.subscribe('消息名称',function(data){
    
    });//订阅

PubSUb.publish('消息名称',data)//发布消息

Code example:
For example, there are two sibling components, Search and List components. After Search queries the data, it transmits values ​​to the List component by publishing messages, and the List component receives the Search data by subscribing to messages. The passed value is displayed
The complete code is as follows:
App.js

import React, {
    
     Component } from 'react'
import Search from './components/Search'
import List from './components/List'

export default class App extends Component {
    
    
  render() {
    
    
    return (
      <div>
        <Search/>
        <List/>
      </div>
    )
  }
}

Search.jsx:

import React, {
    
     Component } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'//引入

export default class Search extends Component {
    
    
    //获取用户数据
   getUserInfo = ()=>{
    
    
    //发布消息PubSUb.publish('消息名称',data)//发布消息
    //注:消息名称要和订阅此消息的组件的消息名称一致
    // PubSub.publish('getMessage',{name:'wangdada',age:18})
    axios.get('/api2/api/user').then(res=>{
    
    
      console.log(res,'返回的数据')
      //获取到数据发布消息
      PubSub.publish('getMessage',{
    
    users:res.data.res})
    },err=>{
    
    
      console.log(err,'请求失败')
    })
  }
  render() {
    
    
    return (
      <div>
          <button onClick={
    
    this.getUserInfo}>查数据</button>
      </div>
    )
  }
}

List.jsx:

import React, {
    
     Component } from 'react'
import PubSub from 'pubsub-js'//引入
export default class List extends Component {
    
    
  //状态
   state = {
    
    //初始化状态
      users:[],//users初始值为数据
  }

  //生命周期函数componentDidMount进行初始化相关,如消息订阅
  componentDidMount(){
    
    
      //消息订阅PubSUb.subscribe('消息名称',function(data){});//订阅
    this.token =  PubSub.subscribe('getMessage',(_,stateObj)=>{
    
    
        //更新状态
        this.setState(stateObj)
        console.log(this.state.users,'订阅消息获取到数据')
    })
  }
  //取消订阅
  componentWillUnmount(){
    
    
    PubSub.unsubscribe(this.token)
  }

  render() {
    
    
    //从状态中读取数据
    const{
    
    users} = this.state
    return (
    <div>
        {
    
    
            users.map((obj)=>{
    
    
                return <h2>姓名:{
    
    obj.username}</h2>
            })
        }
    </div>
    )
  }
}

The effect is as follows:
Insert image description hereBrother, try it now! ! !

Guess you like

Origin blog.csdn.net/qq_41497443/article/details/124722246
Recommended