【发布时间】:2016-06-27 05:22:10
【问题描述】:
所以我的服务器向客户端发送一个 json 编码的数组。
客户端在上面使用 JSON.parse,但是当我尝试提取数据时出现错误:TypeError: Cannot read property 'description' of undefined,但我确定描述是关键之一,因为运行:
和reactjs有关系吗?我的代码:
<script type="text/jsx">
/** @jsx React.DOM */
var HabitModel = React.createClass({
getInitialState: function(){
return {
data: [],
pageAmount: 0
};
},
componentDidMount: function(){
this.serverRequest = $.get(this.props.source, {userid:123}, function(result){
result = JSON.parse(result);
this.setState({
data: result,
pageAmount: Math.ceil(result.length/4)
});
}.bind(this));
},
render: function() {
return (
<div>
the habit is:
<HabitList data={this.state.data} />
</div>
);
}
})
var HabitList = React.createClass(
{
render: function(){
return(
{ //error line here
JSON.stringify(this.props.data[0].description)
}
)
}
});
React.render(
<HabitModel source = "/health1/server/habit/user"/>,
document.getElementById('myDiv')
);
</script>
错误在JSON.stringify(this.props.data[0].description)这一行
如果我输入this.props.data[0],它会完美运行,它会输出如下 JSON:
{"habitid":"1","userid":"123","description":"go to the gym","startDate":"0000-00-00","goalDate":"0000-00-00"}
如您所见,其中一个关键是描述。那么this.props.data[0].description 怎么不工作了呢?
编辑: 我发现如果我要在 ajax 调用之后立即执行 console.log
componentDidMount: function(){
this.serverRequest = $.get(this.props.source, {userid:123}, function(result){
result = JSON.parse(result);
console.log(result[0].description); //ADDED LINE, this would work
this.setState({
data: result,
pageAmount: Math.ceil(result.length/4)
});
}.bind(this));
},
这将认识到描述是关键之一。 reactjs 是怎么回事?
【问题讨论】:
-
this.props 或 this.props.description[0] 似乎没有描述属性。使用console.log正确调试...
-
this.props.description的实际形状是什么?这个错误意味着this.props.description[0]是undefined。 -
this.props.description[0] 很好,因为我可以使用 JSON.stringify 从中读取,正如您在帖子中看到的那样。 this.props.description 的实际形状是 [{"habitid":"1","userid":"123","description":"go to the gym","startDate":"0000-00-00" ,"goalDate":"0000-00-00"},{"habitid":"2","userid":"123","description":"努力学习","startDate":"0000-00-00 ","goalDate":"0000-00-00"},{"habitid":"3","userid":"123","description":"去公园","startDate":"0000- 00-00","goalDate":"0000-00-00"} [...] ]
-
我明白为什么会出现混淆,这是我的变量命名。我将更改变量以使其更易于理解
-
@carlosDelgado,虽然它确实有 description 属性,这就是为什么我在帖子中展示了当我做
console.log JSON.stringify(this.props.data[0])时得到的输出
标签: javascript json reactjs