javascript - Reactjs working with sockets: rerender when socket receive a message -


i'm try implement chat application usage of websockets. when websocket got message, no components rerendering. please review code

# main ancestor, chat application @chat = react.createclass   componentwillmount: ->     @setstate signals: [] # list of signals received websockets      socket = new websocket('ws://localhost:19108')     socket.onmessage = (event) =>       @state.signals.push { message: event.data, direction: 'in' }       console.log @state.signals # regularly write message console after receiving socket message      @setstate socket: socket   render: ->     <div>       <div classname="row">         <div classname="col-md-12">           <signallist signals={@state.signals} /> # pass signals here         </div>       </div>     </div>  $ ->   react.render(<chat />, document.getelementbyid('container')) 

signal list try show changes of props, no success. it's still empty array

@signallist = react.createclass   render: ->     <div>{ @props }</div> 

i want props rerendering after each message received websockets. how can that?

you shouldn't mutate @state directly, instead use setstate enqueue state update which, once performed, cause component re-render. should consider @state , value read-only of time.

in case, replace

@state.signals.push { message: event.data, direction: 'in' } 

with

@setstate signals: @state.signals.concat([{ message: event.data, direction: 'in' }]) 

unlike array::push, array::concat has benefit of not mutating source array, means @state.signals stays unchanged until state update has been performed.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -