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])}); }
Thanks for sharing this tricks. It is really helpful.
ReplyDeleteReact js Training | React js course
I had got a clear idea of what the blog is all about. Kindly continue doing more.
ReplyDeleteTOEFL Coaching in Chennai
Best TOEFL Coaching Institute in Chennai
TOEFL Classes in Chennai
TOEFL Training in Chennai
IELTS Classes in Mumbai
Spoken English Classes in JP Nagar
Spoken English Class in Thiruvanmiyur
Spoken English Classes in Chennai
English Speaking Classes in Mumbai
ReplyDeleteI have never seen a article like this with more involvement in reading from my side. Amazing!!!!
Hadoop Training in Chennai
Big data training in chennai
big data training in velachery
JAVA Training in Chennai
Python Training in Chennai
Software testing training in chennai
Hadoop training in chennai
Big data training in chennai
big data training in chennai anna nagar
movies whatsapp groups
ReplyDelete