javascript - Understanding how Ajax success callback updates state in this ReactJS example -
i working thought reactjs tutorial. trying understand how commentform component submits (or updates server) data has collected via passing commentbox.
here 2 components work reference:
var commentform = react.createclass({ handlesubmit: function(e) { e.preventdefault(); var author = react.finddomnode(this.refs.author).value.trim(); var text = react.finddomnode(this.refs.text).value.trim(); if (!text || !author) { return; } this.props.oncommentsubmit({author: author, text: text}); react.finddomnode(this.refs.author).value = ''; react.finddomnode(this.refs.text).value = ''; return; }, render: function() { return ( <form classname="commentform" onsubmit={this.handlesubmit}> <input type="text" placeholder="your name" ref="author" /> <input type="text" placeholder="say something..." ref="text" /> <input type="submit" value="post" /> </form> ); } }); var commentbox = react.createclass({ loadcommentsfromserver: function() { $.ajax({ url: this.props.url, datatype: 'json', cache: false, success: function(data) { this.setstate({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.tostring()); }.bind(this) }); }, handlecommentsubmit: function(comment) { $.ajax({ url: this.props.url, datatype: 'json', type: 'post', data: comment, success: function(data) { this.setstate({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.tostring()); }.bind(this) }); }, getinitialstate: function() { return {data: []}; }, componentdidmount: function() { this.loadcommentsfromserver(); setinterval(this.loadcommentsfromserver, this.props.pollinterval); }, render: function() { return ( <div classname="commentbox"> <h1>comments</h1> <commentlist data={this.state.data} /> <commentform oncommentsubmit={this.handlecommentsubmit} /> </div> ); } }); my source of confusion comes handlecommentsubmit in commentbox component, ajax success callback.
since set data: comment, data merely comment form collected. on success take data , this.setstate({data: data});. wouldn't setting state 1 comment (the 1 collected in form?). wouldn't need pull server of data, including post made loadcommentsfromserver? how work?
since set data: comment, data merely comment form collected. on success take data , this.setstate({data: data});. wouldn't setting state 1 comment (the 1 collected in form?).
no, in example, comment passed in function setting data property ajax request. data parameter in success callback data ajax response.
so, here setting data state property whatever server responds with. think example assumes server reflecting same comment, allows server save comment during http call.
Comments
Post a Comment