Three ways of React component communication

Three communication methods of React components

The first type: pass general data or functions through prop

Passing data through props can only be passed layer by layer.For example, if the grandchild component needs to update the state of the parent component, it needs to call the update state method of the parent component. In this case, the parent component must pass the update function as a prop to the child component, and the child component passes the update function from the parent component in the prop to the grandchild component, which is called layer by layer. But this is too cumbersome, and the second one is given below.

The second: through the mechanism of message publishing and subscription

First, you need to download the pubsub-js file from the React project file

npm install pubsub-js --save

Then introduce files into the project

import PubSub from 'pubsub-js' //引入
PubSub.subscribe('delete', function(msg,data){
    
     }); //订阅
PubSub.subscribe('delete', (msg,data)=>{
    
     }); //订阅
PubSub.publish('delete', data) //发布消息

This method needs to pay attention to that the setting of the callback function during message subscription is best done with an arrow function, so that it does not affect the direction of this in the function. Arrow function portal

The third method: redux

……Follow-up update content

Guess you like

Origin blog.csdn.net/qq_44606064/article/details/105279284