当我收听'new-message'
活动时,我正在尝试拨打Dashboard
组件的createMessage
功能:
var socket = io.connect()
socket.on('new-message', (data) => {
console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
Dashboard.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})
const Dashboard = React.createClass({
createMessage: function(id, body, context, urgent, customContext) {
this.setState({
messages: [
...this.state.messages,
{id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
]
})
}
})
但是,我收到错误:Uncaught TypeError: Dashboard.createMessage is not a function
有没有办法从组件外部访问Dashboard
createMessage
方法?
或者有办法让Dashboard
component
总是听一个事件,我可以做这样的事情:
var socket = io.connect()
const Dashboard = React.createClass({
alwaysListenForEvent: function() {
socket.on('new-message', (data) => {
console.log("ALL CLIENTS SHOULD GET THIS MESSAGE")
this.createMessage(data.id, data.body, data.context, data.urgent, data.customContext)
})
}
createMessage: function(id, body, context, urgent, customContext) {
this.setState({
messages: [
...this.state.messages,
{id: id, user_id: this.state.currentUser, body: body, context: context, urgent: urgent, customContext: customContext}
]
})
}
})
答案 0 :(得分:0)
您可以使用套接字HoC或container component来包装信息中心组件。
示例代码:
2009-04-01 00:00:00
<type 'datetime.datetime'>
这样,您的仪表板组件无需了解有关消息的任何信息。