Sono un principiante di ReactJS e sto appena iniziando con the example code on React's official site. Quando sto provando il codice nella sezione 'Fetching from the server', non riesco a farlo funzionare.ReactJS non recupera i dati dal server quando si utilizza l'attributo 'url'
Ho provato sia il percorso relativo
React.render(
<CommentBox url="../data/data.json" />,
document.getElementById('content')
);
e percorso assoluto
React.render(
<CommentBox url="http://localhost/path/to/data.json" />,
document.getElementById('content')
);
Ma nessuno di loro ha funzionare correttamente. Quando ho estratto il pannello Rete nello strumento di sviluppo di Chrome, ho visto che la pagina non inviava nemmeno la richiesta di data.json
. Quindi ho ricevuto un errore di Cannot read property 'comments' of undefined
. più
codice:
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')
);
});
sarà apprezzato Qualsiasi tipo di aiuto.
Grazie.
Puoi condividere più del tuo codice? Stai facendo una richiesta 'GET' nel tuo componente per recuperare i dati' JSON'? Ecco un [ottimo esempio] (http://facebook.github.io/react/tips/initial-ajax.html) su come recuperare i dati dal server. –
@BrettDeWoody VERAMENTE un grande esempio per un principiante come me. Grazie! :) – hudidit
Ho pensato esattamente la stessa cosa, grazie per il tuo post :) :) – Rocklan