Move initial $.ajax out of getInitialState
We want to encourage people to make pure getInitialState functions.
Ben Alpert committed
Dec 29, 2013 at 00:14 UTC
cce91611aae95fecd73616ae5e60480c6d2890ba
1 file changed
+7
-5
docs/docs/tutorial.md
+7
-5
@@ -374,14 +374,17 @@ When the component is first created, we want to GET some JSON from the server an
374
]
375
```
376
377
-We will use jQuery to help make an asynchronous request to the server.
377
+We'll use jQuery to help make an asynchronous request to the server.
378
379
Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
380
381
-```javascript{4-10}
381
+```javascript{6-17}
382
// tutorial13.js
383
var CommentBox = React.createClass({
384
getInitialState: function() {
385
+ return {data: []};
386
+ },
387
+ componentWillMount: function() {
388
$.ajax({
389
url: 'comments.json',
390
dataType: 'json',
@@ -392,7 +395,6 @@ var CommentBox = React.createClass({
395
console.error("comments.json", status, err.toString());
396
}.bind(this)
397
});
395
- return {data: []};
398
},
399
render: function() {
400
return (
@@ -406,9 +408,9 @@ var CommentBox = React.createClass({
408
});
409
```
410
409
-The key is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
411
+Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
412
411
-```javascript{3,14-17,30}
413
+```javascript{3,15-16,30}
414
// tutorial14.js
415
var CommentBox = React.createClass({
416
loadCommentsFromServer: function() {