This is the 12th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021″

use

  • When we want the parent component to pass value to the child component, we usually use props to pass value.
  • When a child component passes a value to its parent, an event in the child component usually triggers a callback function (also known as props), and the corresponding function in the parent component changes the value.
  • I usually pass the value of child A back to the parent, which then passes it back to child B

All three of these situations can be addressed using message subscribe and publish mechanisms.

  • Of course it’s better to use props for father to son.
  • The children pass values to the parent, publish in the child, subscribe in the parent, and get the corresponding values
  • Values are passed between sibling components, published in child component A, and subscribed in child component B

News subscription

Here’s an example:

Subscribe to the newspaper

  • The money, the address, the newspaper subscription
  • The postman delivers newspapers

Subscribe to messages:

  • The name of the message
  • news

use

Many libraries implement this mechanism, and we use PubSub, which is widely used

The installation

npm install pubsub-js
yarn add pubsub-js
Copy the code

The introduction of

import PubSub from 'pubsub-js';
Copy the code

implementation

Publish (App) in parent, subscribe (Data) in child

App (parent) component

class App extends React . Component  {
  componentDidMount() {
  // publish publish message name: publish_one Content: This is publish
      PubSub.publish("publish_one"."This is publish")}render() {
    return (
      <div className = 'ArticleContainer'>
        <Data/>
      </div>)}}Copy the code

Data (child) component

lass Data extends React.Component{
  state={
    publishData:' '
  }
  componentDidMount(){
   // Subscribe message message name: publish_one The second argument is a function
   This function takes two more arguments: the message name and the message data
    PubSub.subscribe("publish_one".(msg,data) = >{
      this.setState({publishData:data})
    })
  }
  render(){
    return(
    <div>
      {this.state.publishData}
    </div>)}}Copy the code

Define the token

If we go to GitHub to check its documentation, we can find that it converts the subscribe variable into a token, which is just like the use of timer method. For us to cancel timer/subscribe.

componentDidMount(){
    this.token = PubSub.subscribe('publish_one'.(msg,data) = >{
       this.setState({publishData:data})
    })
}
Copy the code

At some point you need to unsubscribe

To conserve resources, we sometimes need to unsubscribe. The token variable we defined is useful

componentWillUnmount(){
     PubSub.unsubscribe(this.token)
 }
Copy the code