2017-03-31 76 views
0

陣營組件當我聽到一個'new-message'事件我想打電話給我Dashboard組件的createMessage功能:訪問從插座IO聽衆

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

是否有從組件外部訪問DashboardcreateMessage方法的方法?

或者是有辦法有Dashboardcomponent總是監聽事件,我可以做這樣的事情:

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

你可以用一個Socket HoCcontainer component包裝你的儀表板組件。

示例代碼:

class SocketListener extends React.Component { 
    state = { 
    messages: [] 
    } 
    componentDidMount() { 
    socket.on('new-message', (data) => { 
     this.setState({ messages: this.state.messages.concat(data) }) 
    }); 
    } 

    render() { 
    return (
     <Dashboard 
     messages={this.state.messages} 
     /> 
    ) 
    } 
} 

這樣,你的儀表板組件並不需要知道消息什麼。