|
@@ -6,7 +6,8 @@ Good practices:
|
|
|
|
|
|
State
|
|
State
|
|
- direct reads, write through setState()
|
|
- direct reads, write through setState()
|
|
-- declare initial state in constructo()
|
|
|
|
|
|
+- declare initial state in constructor()
|
|
|
|
+- setState() calls render(): beware loops = avoid it in render()
|
|
|
|
|
|
Refs:
|
|
Refs:
|
|
- are called by React during render()
|
|
- are called by React during render()
|
|
@@ -16,6 +17,11 @@ Events:
|
|
- React events are "synthetic" events, masking the browser behaviour differences
|
|
- React events are "synthetic" events, masking the browser behaviour differences
|
|
- https://facebook.github.io/react/docs/events.html
|
|
- https://facebook.github.io/react/docs/events.html
|
|
|
|
|
|
|
|
+Lifecycle methods:
|
|
|
|
+- Main: componentWillMount / componentDidMount / componentWillUnmount
|
|
|
|
+- fetch initial data from cWM, start a refresh poll loop from cDM, stop loop from cWU
|
|
|
|
+ - https://facebook.github.io/react/docs/react-component.html
|
|
|
|
+
|
|
JSX:
|
|
JSX:
|
|
- "className", not "class"
|
|
- "className", not "class"
|
|
- knows how to render an array of JSX elements, not just one.
|
|
- knows how to render an array of JSX elements, not just one.
|
|
@@ -74,10 +80,7 @@ class CommentBox extends React.Component {
|
|
super();
|
|
super();
|
|
this.state = {
|
|
this.state = {
|
|
showComments: false,
|
|
showComments: false,
|
|
- comments: [
|
|
|
|
- { id: 1, author: "Morgan McCircuit", body: "great picture!" },
|
|
|
|
- { id: 2, author: "Bending Bender", body: "Excellent stuff" }
|
|
|
|
- ]
|
|
|
|
|
|
+ comments: []
|
|
};
|
|
};
|
|
}
|
|
}
|
|
|
|
|
|
@@ -92,6 +95,17 @@ class CommentBox extends React.Component {
|
|
this.setState({comments: this.state.comments.concat([comment])});
|
|
this.setState({comments: this.state.comments.concat([comment])});
|
|
}
|
|
}
|
|
|
|
|
|
|
|
+ _fetchComments() {
|
|
|
|
+ jQuery.ajax({
|
|
|
|
+ method: "GET",
|
|
|
|
+ url: "/static/comments.json",
|
|
|
|
+ // Arrow function: keep "this" binding to the class instance.
|
|
|
|
+ success: (comments) => {
|
|
|
|
+ this.setState({comments});
|
|
|
|
+ }
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+
|
|
_getComments() {
|
|
_getComments() {
|
|
return this.state.comments.map((comment) => {
|
|
return this.state.comments.map((comment) => {
|
|
return (<Comment
|
|
return (<Comment
|
|
@@ -117,6 +131,18 @@ class CommentBox extends React.Component {
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
|
|
|
|
+ componentDidMount() {
|
|
|
|
+ this._timer = setInterval(() => this._fetchComments(), 5000);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ componentWillMount() {
|
|
|
|
+ this._fetchComments();
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ componentWillUnmount() {
|
|
|
|
+ clearInterval(this._timer);
|
|
|
|
+ }
|
|
|
|
+
|
|
render() {
|
|
render() {
|
|
const comments = this._getComments();
|
|
const comments = this._getComments();
|
|
let buttonText = "Show comments";
|
|
let buttonText = "Show comments";
|