我正在參加reactjs教程here,在完成本教程後,我開始修改一點點。我遇到的一個問題是我無法弄清楚如何索引到某個數組(至少它看起來是一個數組)。下面是當數組從服務器得到的代碼:如何索引到已解析的json數組中
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount
是Reactjs類定義了一個名爲CommentBox
類,被解析JSON文件的部分看起來像
[
{id: 1, author: "Pete Hunt", text: "This is one comment"},
{id: 2, author: "Jordan Walke", text: "This is *another* comment"}
]
所以現在我試圖改變相同的CommentBox
類的render
方法來添加一行來打印數據數組的第一個元素。渲染方法變爲
render: function() {
return (
< div className = "commentBox" >
{this.state.data[0].toString()}
<h1> Comments < /h1>
< CommentList data = {this.state.data}/>
< CommentForm onCommentSubmit = {this.handleCommentSubmit}/>
< /div>
);
}
其中我添加的行是{this.state.data[0].toString()}
。此行導致錯誤,說明this.state.data[0]
未定義。我該如何獲得this.state.data
的元素?它不應該只是一個正常的數組,就好像它是由下面的代碼設置的?
this.state.data = [
{id: 1, author: "Pete Hunt", text: "This is one comment"},
{id: 2, author: "Jordan Walke", text: "This is *another* comment"}
];
這固定了它。我之前並沒有使用ajax,所以我不知道它是如何工作的。 –