Tôi là người mới bắt đầu của ReactJS và chỉ bắt đầu với the example code on React's official site. Khi tôi đang thử mã trong phần 'Fetching from the server', tôi không thể làm cho nó hoạt động.ReactJS không tìm nạp dữ liệu từ máy chủ khi sử dụng thuộc tính 'url'
Tôi đã thử cả đường dẫn tương đối
React.render(
<CommentBox url="../data/data.json" />,
document.getElementById('content')
);
và đường dẫn tuyệt đối
React.render(
<CommentBox url="http://localhost/path/to/data.json" />,
document.getElementById('content')
);
Nhưng none trong số họ đã chạy một cách chính xác. Khi tôi đã kiểm tra Bảng điều khiển mạng trong công cụ Chrome dev, tôi thấy trang thậm chí không gửi yêu cầu cho data.json
. Do đó, tôi gặp lỗi Cannot read property 'comments' of undefined
. nhiều mã
:
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
from {this.props.author} <br/>
{this.props.children}
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.comments.map(function(comment){
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
return (
<div className="comment-list">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
render: function() {
return (
<div className="comment-form">
Hello, I am a comment form.
</div>
);
}
});
var CommentBox = React.createClass({
render: function() {
return (
<div className="comment-box">
<h1>Comments</h1>
<CommentList comments={this.props.data.comments} />
<CommentForm />
</div>
);
}
});
// ========== This won't work ===========
// React.render(
// <CommentBox url="./data/data.json" />,
// document.getElementById('content')
//);
// =========== This works. ===========
$.ajax({
type: "GET",
url: "./data/data.json",
dataType: "json",
}).done(function(res){
React.render(
<CommentBox data={res} />,
document.getElementById('content')
);
});
Bất kỳ loại trợ giúp sẽ được đánh giá cao.
Cảm ơn.
Bạn có thể chia sẻ nhiều mã hơn không? Bạn có đang thực hiện yêu cầu 'GET' trong thành phần của mình để truy xuất dữ liệu' JSON' không? Đây là [ví dụ tuyệt vời] (http://facebook.github.io/react/tips/initial-ajax.html) về cách truy xuất dữ liệu từ máy chủ. –
@BrettDeWoody REALLY là ví dụ tuyệt vời cho người mới bắt đầu như tôi. Cảm ơn bạn! :) – hudidit
Tôi nghĩ chính xác điều tương tự, cảm ơn bài đăng của bạn :) :) – Rocklan