浏览代码

load comments from json

Lucas Stadler 11 年之前
父节点
当前提交
8a83c48c5d
共有 2 个文件被更改,包括 33 次插入8 次删除
  1. 12 0
      js/react/comments.json
  2. 21 8
      js/react/entry.js

+ 12 - 0
js/react/comments.json

@ -0,0 +1,12 @@
1
[
2
	{
3
		"author": "Alice",
4
		"text": "Down the... halfpipe!"
5
	}, {
6
		"author": "PP",
7
		"text": "Alice, what **blasphemy**!"
8
	}, {
9
		"author": "Maybe Not Lewis",
10
		"text": "Let her be herself, Peter, we let *you* jump around all the time as well..."
11
	}
12
]

+ 21 - 8
js/react/entry.js

@ -34,11 +34,30 @@ class CommentList extends React.Component {
34 34
}
35 35
36 36
class CommentBox extends React.Component {
37
	constructor(props) {
38
		super(props);
39
		this.state = {data: []}
40
	}
41
42
	componentDidMount() {
43
		let xhr = new XMLHttpRequest();
44
		xhr.open('GET', this.props.url);
45
		xhr.onreadystatechange = function() {
46
			if (xhr.readyState == XMLHttpRequest.DONE) {
47
				this.setState({data: JSON.parse(xhr.responseText)});
48
			}
49
		}.bind(this);
50
		xhr.onerror = function(err) {
51
			console.error(this.props.url, xhr.status, err);
52
		}.bind(this);
53
		xhr.send();
54
	}
55
37 56
	render() {
38 57
		return (
39 58
			<div className="comment-box">
40 59
				<h1>Comments</h1>
41
				<CommentList data={this.props.data} />
60
				<CommentList data={this.state.data} />
42 61
				<CommentForm />
43 62
			</div>
44 63
		);
@ -57,10 +76,4 @@ class Comment extends React.Component {
57 76
	}
58 77
}
59 78
60
var data = [
61
	{author: "Alice", text: "Down the... halfpipe!"},
62
	{author: "PP", text: "Alice, what **blasphemy**!"},
63
	{author: "Maybe Not Lewis", text: "Let her be herself, Peter, we let *you* jump around all the time as well..."}
64
];
65
66
React.render(<CommentBox data={data} />, document.getElementById("content"));
79
React.render(<CommentBox url="comments.json" />, document.getElementById("content"));