Passing values (communication) between sibling components
Passing values between parent and child components: With the help of props, the child passes a function to the parent with props, and the child component calls the function and passes parameters.
Passing values between sibling components: message subscription and publishing mechanism.
PubSub is not only suitable for passing values between sibling components, but also for passing values between any components, especially for passing messages in multi-level hierarchical components, because it doesn’t matter where the components are.
Message Subscription and Publishing
Tool library: PubSubJS (PubSub is the abbreviation of Publish and Subscribe)
Download:
npm install pubsub-js --save
Steps for usage:
Introduce
import PubSub from 'pubsub-js'
(the repository name of a technology is different from the npm name, because of the npm specification)Subscribe
PubSub.subscribe{'delete', function(data){}};
Publish a message
PubSub.publish('delete', data)
PubSub use
Subscribe messages in components that need to receive data
1
2
3
4var mySubscriber = function(msg, data){ //Parameter 1 is the message name (useless, available _, placeholder), and parameter 2 is the data.
console.log(msg, data)
}
var token = PubSub.subscribe("My Topic", mySubscriber); //Parameter 1 is the message name, and parameter 2 is the callback function that will be called when someone publishes a message. Assigned to token is used when unsubscribing later.mySubscriber is usually written directly in the PubSub.subscribe method, and is usually subscribed after the component is mounted. After the code is simplified:
1
2
3
4
5componentDidMount(){
let token = PubSub.subscribe("My Topic 1", (_, data) => {
console.log(data);
})
}Cancel subscription: usually before the component is unloaded.
1
2
3componentWillUnmount(){
PubSub.unsubscribe(token)
}
Post a message in the component that generates the data
1
PubSub.publish("My Topic", 'hello world!'); //Parameter 1 is the message name, parameter 2 is the sent data, usually {}