reactJs:两个不同组件之间的通信

Pri*_*iya 2 reactjs

我是反应灵的新手.我希望在两个独立组件之间进行通信.

这些组件没有任何父子关系.

我找到了这段代码.

我不知道如何使用它 https://medium.com/react-zine/how-to-communicate-between-components-in-react-cc1ee986523a

Dav*_*ing 12

来自文档:

对于没有父子关系的两个组件之间的通信,您可以设置自己的全局事件系统.订阅componentDidMount()中的事件,取消订阅componentWillUnmount(),并在收到事件时调用setState().通量模式是安排这种方式的可能方式之一.

我们使用PubSub模式来附加全局事件,但正如文档所说,您可以使用许多不同的安排.

使用PubSub的示例

接收器组件:

componentDidMount: function() {
    this.token = PubSub.subscribe('MY TOPIC', this.subscriber)
},
componentWillUnmount: function() {
    PubSub.unsubscribe(this.token)
},
subscriber: function(msg, data) {
    console.log(msg, data)
    // set state etc...
})
Run Code Online (Sandbox Code Playgroud)

发射器:

PubSub.publish('MY TOPIC', 'hello world!')
Run Code Online (Sandbox Code Playgroud)