javascript - How to update state of reactjs app by building on existing state? -


i writing reactjs chat client , came across this in documentation, says

never mutate this.state directly, calling setstate() afterwards may replace mutation made. treat this.state if immutable.

setstate() not mutate this.state creates pending state transition. accessing this.state after calling method can potentially return existing value.

there no guarantee of synchronous operation of calls setstate , calls may batched performance gains.

setstate() trigger re-render unless conditional rendering logic implemented in shouldcomponentupdate(). if mutable objects being used , logic cannot implemented in shouldcomponentupdate(), calling setstate() when new state differs previous state avoid unnecessary re-renders.

when message sent function called:

sendmessage: function(msg) {     //update state of app     var message = {username:'user', message:msg};     console.log(message.tostring());     this.state.datas.push(message);     this.setstate({datas: this.state.datas});   }, 

what trying append new message list of messages reset state components rerender. works fine based on documentation quoted above isn't how should done. how should go updating list of messages , updating state without directly calling this.state.datas.push(message)?

you can append new message inside setstate using concat. way not mutating state directly since concat returns new array

sendmessage: function(msg) {     //update state of app     var message = {username:'user', message:msg};     this.setstate({datas: this.state.datas.concat([message])}); } 

Comments

Post a Comment

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -